javascript - ng-repeat 项目在父指令的链接后功能中不可用

标签 javascript angularjs angularjs-directive

我想在“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>

骗子:https://next.plnkr.co/edit/99qi4eliISMeEWD2?preview

最佳答案

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/

相关文章:

angularjs - Angular(指令新手): How to add date time-picker to ngModel so that it can be validated?

javascript - 为什么我不能让这个应用程序使用 webpack 和很棒的 typescript 加载器将 typescript 文件编译成 javascript?

java - 将 React 与 Nashorn 一起使用会抛出 "ReferenceError: "控制台“未定义”

angularjs - onsen navigator popPage,重新加载之前的 Controller

javascript - Protractor - 错误 : Index out of bound exception while using the same function for the second time

angularjs - 编译后多次执行On事件

javascript - 单击按钮上的 Bootstrap 完整日历 View

javascript - ExpressJS 链 promise 多次调用 next() 函数

javascript - 如何在 iframe 中维护 Angular 应用程序的页面重新加载路线?

html - 无法设置默认文本框值