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>

柱塞:https://next.plnkr.co/edit/99qi4eliISMeEWD2?preview

daodan_9 回答:ng-repeat项在父指令的后链接功能中不可用

  

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>

myFocus指令将元素添加到DOM时,ng-repeat指令将添加事件处理程序。

本文链接:https://www.f2er.com/2985402.html

大家都在问