ng-Repeat Special Variables in AngularJS

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

  • $index
  • $first
  • $middle
  • $last

  1. <html>  
  2.     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
  3.   
  4.     <head>  
  5.         <script>  
  6.         var app = angular.module("app", []);  
  7.         app.controller("ctrl", function ($scope)  
  8.         {  
  9.             $scope.employees = [  
  10.             {  
  11.                 name: 'A',  
  12.                 gender: 'boy'  
  13.             },  
  14.             {  
  15.                 name: 'B',  
  16.                 gender: 'girl'  
  17.             },  
  18.             {  
  19.                 name: 'C',  
  20.                 gender: 'boy'  
  21.             },  
  22.             {  
  23.                 name: 'D',  
  24.                 gender: 'boy'  
  25.             }];  
  26.         });  
  27.         </script>  
  28.     </head>  
  29.   
  30.     <body ng-app="app">  
  31.         <div ng-controller="ctrl">  
  32.             <ul>  
  33.                 <li ng-repeat="employee in employees">  
  34.                     <div> {{employee.name}} is a {{employee.gender}}. <span ng-if="$first">  
  35.                         <strong>(first element found)</strong>  
  36.                         </span> <span ng-if="$middle">  
  37.                         <strong>(middle element found)</strong>  
  38.                         </span> <span ng-if="$last">  
  39.                         <strong>(last element found)</strong>  
  40. <                     /span> </div>  
  41.                 </li>  
  42.             </ul>  
  43.         </div>  
  44.     </body>  
  45.   
  46. </html>  
Output

A is a boy. (first element found)
B is a girl. (middle element found)
C is a boy. (middle element found)
D is a boy. (last element found)