Browse Articles

Understanding ng-repeat special variables

04 Aug 2022
Intermediate
19.6K Views

The ng-repeat directive has a set of special variables which you are useful while iterating the collection. These variables are as follows:

  1. $index

  2. $first

  3. $middle

  4. $last

The $index contains the index of the element being iterated. The $first, $middle and $last returns a boolean value depending on whether the current item is the first, middle or last element in the collection being iterated.

<html>
<head>
 <title></title>
 <script src="lib/angular.js"></script>
 <script>
 var app = angular.module("app", []);

 app.controller("ctrl", function ($scope) {
 $scope.friends = [{ name: 'shailendra', gender: 'boy' },
 { name: 'kiran', gender: 'girl' },
 { name: 'deepak', gender: 'boy' },
 { name: 'pooja', gender: 'girl' }];
 });
 </script>
</head>
<body ng-app="app">
 <div ng-controller="ctrl">
 <ul class="example-animate-container">
 <li ng-repeat="friend in friends">
 <div>
 [{{$index + 1}}] {{friend.name}} is a {{friend.gender}}.

 <span ng-if="$first">
 <strong>(first element found)</strong>
 </span>
 <span ng-if="$middle">
 <strong>(middle element found)</strong>
 </span>
 <span ng-if="$last">
 <strong>(last element found)</strong>
 </span>
 </div>
 </li>
 </ul>
 </div>
</body>
</html>

How it works..

What do you think?

I hope you have enjoyed the ng-repeat directives a special variable in AngularJS while using ng-repeat while developing your app with AngularJS. I would like to have your feedback for this artcle from your side. Your valuable feedback, question, or comments about this article are always welcome.

Even though before Anguar2 revulution, I have curated various angular js online training video based learning materials with hands-on coding with real-time implemention in a step by step angularJs training program. on the demand from angular js training in Hyderabad audience, I made freely available at Dot Net Tricks & youtube. Hope you will refer Angularjs training videos.

Thank you so much!

Learn to Crack Your Technical Interview

Accept cookies & close this