javascript - ng-repeat 项目在父指令的链接后功能中不可用
问题描述
我想在“托管”指令的函数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>
Plunker:https ://next.plnkr.co/edit/99qi4eliISMeEWD2?preview
解决方案
有什么
ng-repeat
不同吗?
根据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>
当指令将元素添加到 DOM时,该myFocus
指令将添加事件处理程序。ng-repeat
推荐阅读
- mysql - 将 MySQL 数据库函数 (?) 与 SQLite (Node.js) 一起使用
- node.js - this._verify 不是登录功能
- reactjs - Redux-form 如何更新 Material-UI v4 textField 值?
- google-cloud-firestore - Javascript Firestore 客户端是否缓存文档引用?
- c# - 带有 .NET Framework 的 AWS Lambda 函数
- r - 在 dplyr 中,如何根据某一列是否在数据框中选择和过滤不同的列?
- scala - vert.x scala 可以热重载吗?
- java - JavaFX 为 GridPane 中的项目设置边距
- python - 通过 Django 中的 api 在多对多字段中添加新项目
- google-sheets - 在 Google 电子表格中使用趋势线预测 LTV