How to Create ng-repeat Last Item Callback Function in AngularJS

There are various scenarios where we will need to execute a callback function just after the last element like attaching events to it or some other DOM manipulation.

Let’s get started.

First of all, we need to create simple directive for it

angular.module('directives.utils', [])
    .directive('onLastRepeat', function() {
        return function(scope, element, attrs) {
            if (scope.$last) setTimeout(function() {
                scope.$emit('onRepeatLast', element, attrs);
            }, 1);
        };
});

Then in the view, we can use it just like this

<div ng-repeat="item in products" on-last-repeat>
...
</div>

And the callback function in the controller

$scope.$on('onRepeatLast', function(scope, element, attrs) {
 // Do some stuffs here
}

That’s all… Now you can use it whenever you need it.