【问题标题】:ng-repeat items not available in post-link function of parent directiveng-repeat 项目在父指令的链接后功能中不可用
【发布时间】:2019-12-03 13:33:30
【问题描述】:

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

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

【问题讨论】:

  • 在某些情况下 dom 在 link func 中没有准备好。您将需要使用 '$timeout' 来确保
  • 感谢比尔,您的建议。我已经发现它可以与 $timeout 一起使用,但是我想知道,什么情况下 DOM 在链接中不可用以及为什么。使用 $timeout 对我来说有点 hacky,虽然它绝对是快速的解决方案。
  • 感谢 Allabakash,我浏览了答案并找到了“解决方法”。虽然我想知道为什么ng-repeat 很特别。

标签: javascript angularjs angularjs-directive


【解决方案1】:

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 指令将在 ng-repeat 指令将元素添加到 DOM 时添加事件处理程序。

【讨论】:

  • 感谢您的回答,但我有一个后续问题。什么时候将 DOM 前置项添加到页面中?它是否发生在指令生命周期功能(编译、控制器、预链接、后链接)之外?我在ng-repeat docs 上找不到任何信息。
猜你喜欢
  • 2015-07-26
  • 2013-01-27
  • 2014-04-02
  • 2013-07-12
  • 1970-01-01
  • 1970-01-01
  • 2014-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多