我在指令模板中使用 ng-repeat
。
myApp.directive("test", function () {
return {
restrict: 'C',
scope: {
bindVar: '='
},
template: '<div>\
<div class="item" ng-repeat="sel in bindVar">{{sel.display}}</div>\
</div>',
link: function ($scope, element, attrs) {
// setTimeout(function() {
alert($('.item').length); // <--- RETURNS 0, IF I ADD TIMEOUT RETURNS 3
// },0);
} // of link
} // of return
});
http://jsfiddle.net/foreyez/t4590zbr/
但是,当 link()
函数被调用时,我似乎无法访问已创建的项目。为此,我需要将超时设置为 0(在它起作用之后)。
我在以下文章中读到:http://lorenzmerdian.blogspot.com/2013/03/how-to-handle-dom-updates-in-angularjs.html
我还看到了一个类似的 Stack Overflow 答案,其中 OP 将超时标记为答案:DOM elements not ready in AngularJS Directive's link() function
但是来吧,必须有另一种方式!
我祈祷这个 hacky 解决方案是错误的,并且当通过指令创建 DOM 时,angular 可以通过某种方式提供回调。或者我真的依赖 .. 超时? (真的吗?:/)
最佳答案
$timeout
实际上是当您使用内联 template
(与 templateUrl
相对)时解决此问题的合法方法。它不会产生竞争条件。
发生的事情是,Angular 遍历 DOM 并收集指令及其前后链接函数(通过编译指令)。然后,执行每个节点(即 DOM 元素)的每个指令的链接函数。
通常,节点的模板(指令所应用的)已经是 DOM 的一部分。因此,如果您有以下指令:
.directive("foo", function(){
return {
template: '<span class="fooClass">foo</span>',
link: function(scope, element){
// prints "<span class="fooClass">foo</span>"
console.log(element.html());
}
}
}
它可以找到 $(".fooClass")
元素。
但是,如果指令使用 transclude: 'element'
,例如 ng-if
( ngIf.js ) 和 ng-repeat
( ngRepeat.js ) 指令执行,Angular 将指令重写为注释 ( compile.js ),因此 $(".item")
(在您的示例中)直到 ng- repeat
把它放在那里。他们在他们的 scope.$watch
函数 ( ngIf.js ) 中这样做,这取决于他们正在观察的值,这可能会在下一个摘要周期发生。因此,即使您的后链接功能运行,您要搜索的实际元素仍然不存在。
.directive("foo", function(){
return {
template: '<span ng-if="true" class="fooClass">foo</span>',
link: function(scope, element){
// prints "<!-- ngIf: true -->"
console.log(element.html());
}
}
}
但是当 $timeout
运行时,它将会存在。
关于javascript - DOM 未在指令的链接函数中准备好。 hacky Timeout 是唯一的解决方案吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28422752/