0

I have the directive, which transcludes an arbitrary content, which should contain some children, that may be created with ngRepeat. Within link or transcludeFn I have access to a template for children, not a finished DOM. Given that, how can I calculate e.g. the sum of .width() of each child?

See http://embed.plnkr.co/o492ObrHC65zbCMxIhxu/

1 Answers1

0

This is an artifact of who ng-repeat and ng-if work - they create a comment and then $watch for a value to either insert or remove an element from the DOM.

So, you are getting the actual DOM of the transcluded element, but it is still in the process of being generated by ng-if/ng-repeat, which have scheduled the generation at the end of the digest cycle.

The quick fix seems to be to use $timeout with 0 seconds. This is not as hacky as it seems - there is no chance of a race condition. All it does is scheduling the function to run at the end of the digest cycle, ensuring that it will see the changes made by ng-repeat and ng-if.

link: function(scope, iElement){

   scope.$watchCollection('items', function () {
      // will not yet have the repeated elements
      console.log("before timeout", iElement.html());
      $timeout(function () {
        // will have all the repeated elements
        console.log("after timeout", iElement.html());
      });
    });
}

plunker

This illustrates, however, that you never know just what transcluded directives are or could be doing - some may change the DOM at a later point in time. The better way is probably to listen to DOM changes and react to that.

New Dev
  • 48,427
  • 12
  • 87
  • 129