首页 > 解决方案 > 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

标签: javascriptangularjsangularjs-directive

解决方案


有什么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


推荐阅读