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

April 15, 2016

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>

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.

👋 I'm Ashik Nesin • Principal Software Engineer @Chargebee 👨‍💻• I write about web development & behinds the scenes of startup/side projects that I'm building

© 2022 Nesin Technologies LLP