Understanding ng-repeat special variables

29 dec. 2023
Intermediate
20,8K Views
2 min read  

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. For a structured and in-depth understanding of AngularJS concepts, consider exploring an Angular Certification program.

Thank you so much!

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Learn to Crack Your Technical Interview

Accept cookies & close this