[英]{{$index}} of ng-repeat computed after linker function of angular directive. $compile it?
HTML
<div repeater ng-repeat='item in items' class='first' id = '{{$index}}' > {{item}} </div>
angularjs指令: -
angular.module('time', [])
.directive('repeater', function() {
var linkFn = function(scope, element, attrs){
var id = $(element).attr('id');
alert(id); // {{$index}}
} ...
在ng-repeat中創建的動態id,當在指令內部顯示為{{$ index}}時,而不是value = 0,1,2 ......
如何確保指令中的鏈接器函數執行時使用動態ID? 我認為可以在指令中使用$ compile來完成。 但我不知道怎么樣?
$compile(element)(scope)
是語法。 但顯然錯誤的順序。
如果您確實需要已經填充了ID,則可以在scope.$evalAsync
運行相關代碼scope.$evalAsync
或$timeout
以確保首先更新綁定。 我建議盡量避免需要檢查DOM並依賴於您的模型來獲取任何此類信息,使用scope.$index
。
當你的鏈接功能到達時,你的指令已經處於編譯過程中並被鏈接,所以我認為重新編譯不會有幫助。 這只是等待足夠長時間來完成鏈接並啟動$digest
,其中屬性將實際更新。 這正是$evalAsync
將為您做的事情。
我希望這能幫到您
指示
angular.module('time', []).directive('repeater', function() { return{ restrict:"E", scope:{ itemarray: "=itemarray" } template:"<div ng-repeat='item in itemarray' class='first' id = '{{$index}}' > {{item}} </div>", link:linkFn } var linkFn = function(scope, element, attrs){ var id = $(element).attr('id'); alert(id); // {{$index}}
} ...
HTML
<repeater itemarray='itemarray"></repeater>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.