我想在“hosting”指令的 post-link
函数中将事件监听器绑定(bind)到 ng-repeat
项上。但是在 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>
最佳答案
Is
ng-repeat
somehow different?
ng-repeat
根据数据添加和销毁 DOM。 .find
操作未找到元素,因为它们尚未添加到 DOM。
在框架将元素添加到 DOM 时调用的指令中添加事件处理程序:
app.directive("myFocus", function() {
return {
link: postLink
};
function postLink(scope, elem attrs) {
elem.on('focus', function() {
console.log('I have focus');
});
}
})
用法
<ul>
<li ng-repeat="item in items">
<a my-focus href="javascript:;">{{item}}</a>
</li>
</ul>
当 ng-repeat
指令将元素添加到 DOM 时,myFocus
指令将添加事件处理程序。
关于javascript - ng-repeat 项目在父指令的链接后功能中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59158322/