我想从“托管”指令的ng-repeat
函数中绑定post-link
个项目上的事件侦听器。但是在post-link
调用期间,ng-repeat
尚未渲染(请参阅plunker中的控制台日志)。
在阅读了有关指令生命周期(https://www.toptal.com/angular-js/angular-js-demystifying-directives)的文章后,我得到了一个印象,即在post-link
中,所有HTML
应该已经可用并且可以添加事件侦听器了。
ng-repeat
是否有所不同?
代码:
angular
.module('myModule',[])
.directive('myDirective',function() {
return {
scope: { items: '=' },restrict: 'E',templateUrl: 'myTemplate.html',link: function (scope,element) {
console.log(element.html());
var anchors = element.find('a');
console.log(anchors);
anchors.on('focus',function() {
console.log('I have focus');
});
}
};
}
);
模板:
<ul>
<li ng-repeat="item in items">
<a href="javascript:;">{{item}}</a>
</li>
</ul>