ng-repeat 项在父指令的 post-link 函数中不可用

ng-repeat items not available in post-link function of parent directive

我想在 "hosting" 指令的 post-link 函数中的 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指令将添加事件处理程序。