我编写自定义指令,我希望我的指令通过生成的ID访问子元素,如下面的代码所示
<div class="my-directive" data-rawdata="user-{{user_id}}">
<div class="raw user-{{user_id}}" id="user-{{user_id}}" style='display:none'>
I'M HERE.
</div>
</div>
这是我的指示:
.directive('myDirective', [function(Cart) {
return {
restrict: 'C',
priority: -1000,
link: function(scope, elem, attrs) {
var element_id = attrs.rawdata
if(element_id){
var found1 = angular.element("#" + element_id); // not found
var found2 = angular.element("." + element_id); // not found
var found3 = angular.element(".raw"); // found
console.log( [found1.length, found2.length, found3.length] );
console.log( found3.attr('id') ); // -> still not compile = user-{{user_id}} ?
console.log( found3.attr('class') ); // -> still not compile = user-{{user_id}} ?
}
}
};
}])
我的指令无法通过id访问元素,因为它还没有完成id的绑定值。
有没有办法让我的指令在绑定完成后执行?我没有运气,试过优先级-1000。
我的plunker是:http://plnkr.co/edit/2J7t6qK7F5MtyWI64Wpa?p=preview
答案 0 :(得分:0)
将您的指令包裹在$timeout
中。这允许链接代码在渲染完成后运行,例如:
$timeout(function(){
if(element_id){
var found1 = angular.element("#" + element_id)
var found2 = angular.element("." + element_id)
var found3 = angular.element(".raw")
console.log( [found1.length, found2.length, found3.length] );
console.log( found3.attr('id') ); // -> still not compile = user-{{user_id}} ?
console.log( found3.attr('class') ); // -> still not compile = user-{{user_id}} ?
if(found1.length)
data = "Your data is " + found1.html()
}
angular.element(".result", elem).html( data || "Data not found" )
}, 0);
也不要忘记将$timeout
注入您的指令。