How to do detect when ngRepeat is finished and after that do something?

Today I am going to show you a simple solution of the problem, presented in the title of this post. You can detect end of ngRepeat with a directive:

app.directive('onLastRepeat', function() {
  return function(scope, element, attrs) {
    if(scope.$last)
      setTimeout(function() {
        scope.$emit('onRepeatLast');
      }, 0);
  }
});

As you can see I firstly check if last item is being processed. If this is true, I set timeout for 0ms. This is an ugly hack, but it works. The problem is that AngularJS has a process named $digest which asynchronously inserts data into template using ngRepeat directive and we don’t know when the process of data insertion is finished. After that we call our function inside of parent scope with $emit and there the magic happens 🙂 (in my case I reseted some widths and heights).

This solution only works if you have one ngRepeat inside of a controller. In other cases you could decide which function to call based on special attributes or something.

Have a nice day! 😉

2 Comments

    • Hi,
      the problem is not which controller calls which function but which “ngRepeat” called mentioned directive. Tnx for additional info!

      Have a nice day!

      Reply

Leave a Comment.