简体   繁体   中英

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

I would like to bind event listeners on ng-repeat items from within post-link function of "hosting" directive. But during post-link call ng-repeat items are not rendered yet (please see console log in plunker).

After reading article on directive life cycle ( https://www.toptal.com/angular-js/angular-js-demystifying-directives ) I got an impression, that in post-link all HTML should be already available and ready for adding event listeners.

Is ng-repeat somehow different?

Code:

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');
              });
          }
      };
    }
  );

Template:

<ul>
  <li ng-repeat="item in items">
    <a href="javascript:;">{{item}}</a>
  </li>
</ul>

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

Is ng-repeat somehow different?

The ng-repeat adds and destroys DOM based on data. The .find operation does not find the elements because they have not been yet added to the DOM.

Add the event handler in a directive which is invoked when the framework adds the element to the DOM:

app.directive("myFocus", function() {
    return {
        link: postLink
    };
    function postLink(scope, elem attrs) {
        elem.on('focus', function() {
            console.log('I have focus');
       });
    }
})

Usage

<ul>
  <li ng-repeat="item in items">
    <a my-focus href="javascript:;">{{item}}</a>
  </li>
</ul>

The myFocus directive will add the event handler when the ng-repeat directive add the element to the DOM.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM