1

So I am trying to use an external library function to create some manipulation in the DOM in one of my controllers that my ng-repeat is connected to. The problem is the following:

I am calling that external function in my controller that adds elements to the ng-repeat array , which in term adds the new elements to the DOM. However, when I am inside the controller, the element does not exist yet, even though I have added it to the array. How can I bound an external function to be called once the element has actually been appended to the DOM, rather than when it was actually added to the array that controls the ng-repeat?

I want to fire the event once the element has actually been created. Any suggestions?

Let me know if you would like to see a fiddle of this idea.

Georgi Angelov
  • 4,338
  • 12
  • 67
  • 96

1 Answers1

2

As mentioned in the comments, a check-last directive that checks for $last can be used to determine when the last iteration of ng-repeat is executing.

.directive('checkLast', function() {
   return function (scope, element, attrs) {
      if (scope.$last === true) {
         element.ready(function() {  // or maybe $timeout
            ... do something ...
         });
      }
   }
});

See also https://stackoverflow.com/a/14656888/215945

Community
  • 1
  • 1
Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
  • My problem is the following: I cannot just use element.ready because in i have an ng-include that is holding the actual element that I want. So the element.ready will be on the parent element but I actually need the child element that is generated through a different template that has no access to the directive. So the directive is hooked to the div parent that has ng-include and so the child element has no access to the directive and so when I try to call that element from the directive, it is not yet created - only the parent is created. I am sure it's kind of confusing. I'll do a fiddle – Georgi Angelov Jul 11 '13 at 13:39
  • do you think $timeout is a bad practice and it may cause problems later on? – Georgi Angelov Jul 11 '13 at 13:41
  • @GeorgiAngelov, sometimes $timeout is necessary (see http://stackoverflow.com/questions/17301572/angularjs-evalasync-vs-timeout/17303759#17303759), but in your case, I think we need to see the fiddle first. Also note that event `$includeContentLoaded` is emitted whenever ng-include content is reloaded. That might help you (not sure). – Mark Rajcok Jul 11 '13 at 14:11
  • @MarkRajock, where would I catch that event? – Georgi Angelov Jul 11 '13 at 14:56
  • @GeorgiAngelov, try to catch it where you want to act on it. If that doesn't work, catch it in the directive that is adding/triggering the ng-include, then throw/broadcast another event (maybe even broadcast it on $rootScope), and then catch that second event someplace else. – Mark Rajcok Jul 11 '13 at 15:28