2015-05-06 30 views
3

如何根據角度js指令獲取綁定的值restrict: 'A'angularjs指令 - 獲取元素綁定的文本內容

<span directiverestrict> {{binding}} </span> 

我試圖使用elem[0].innerText但它返回結合

.directive('directiverestrict',function() { 
    return { 
     restrict:'A', 
     link: function(scope, elem, attr) { 
      // I want to get the value of the binding enclosed in the elements directive without ngModels 
      console.log(elem[0].textContent) //----> returns '{{binding}}' 
     } 
    }; 
}); 
+0

請添加代碼 –

回答

1
<span directiverestrict bind-value="binding"> {{binding}} </span> 

的確切結合'{{binding}}'不是值SCRIPT

directive("directiverestrict", function() { 
    return { 
      restrict : "A", 
      scope : { 
         value : '=bindValue' 
        }, 
      link : function (scope,ele,attr) { 
       alert(scope.value); 
       } 
     } 
}); 
+1

按說我這樣做不想添加任何範圍屬性?以另一種方式獲得它可能嗎? –

+0

請檢查@菲爾編輯 –

2

在鏈接階段內綁定沒有評估,最簡單的方法就是使用$timeout服務延遲的內部評價內容下一消化週期,如

$timeout(function() { 
    console.log(elem[0].textContent); 
},0); 
+1

僅供參考,'0'是默認的超時間隔 – Phil

5

可以使用$interpolate服務,例如

.directive('logContent', function($log, $interpolate) { 
    return { 
    restrict: 'A', 
    link: function postLink(scope, element) { 
     $log.debug($interpolate(element.text())(scope)); 
    } 
    }; 
}); 

Plunker

+0

@ Phil.Nice代碼。@ Michael Rosales請在這裏檢查 –

相關問題