Skip to main content

AngularJs - ng-repeat with $index, $first, $middle, $last, $even, $odd, ng-if, ng-show, ng-hide

Use of ng-repeat Variables:
1.       $index :number ,iterator offset of the repeated element (0...length-1)
2.       $first : boolean true, if the repeated element is first in the iterator.
3.       $middle : boolean true, if the repeated element is between the first and last in the iterator.
4.       $last : Boolean true, if the repeated element is last in the iterator.
5.       $even :Boolean true, if the iterator position $index is even (otherwise false).
6.       $odd :Boolean true, if the iterator position $index is odd (otherwise false).

Example in details,

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<h3>ng-repeat with $index, $first, $middle,$last,$even, $odd, ng-if, ng-show, ng-hide</h3>

<h3>List of Banks :</h3>
<div ng-repeat="bank in banks">{{bank.Id}}. {{bank.Name}}</div>

<h3>ng-repeat with $first : </h3>
<div ng-repeat="bank in banks" ng-if="$first">{{bank.Id}}. {{bank.Name}}</div>

<h3>ng-repeat with $middle :</h3>
<div ng-repeat="bank in banks" ng-if="$middle">{{bank.Id}}. {{bank.Name}}</div>

<h3>ng-repeat with $last :</h3>
<div ng-repeat="bank in banks" ng-if="$last">{{bank.Id}}. {{bank.Name}}</div>

<h3>ng-repeat with $index and $even :</h3>
<div ng-repeat="bank in banks" ng-if="$even">{{$index}}. {{bank.Name}}</div>

<h3>ng-repeat with $index and $odd :</h3>
<div ng-repeat="bank in banks" ng-if="$odd">{{$index}}. {{bank.Name}}</div>

<h2></h2>
<script>
    var app = angular.module("myApp", []);
    app.controller("myCtrl", function($scope) {
      $scope.banks =[
          {"Id":1,"Name":"ICICI Bank"},
          {"Id":2,"Name":"HDFC Bank"},
          {"Id":3,"Name":"HSBC Bank"},
          {"Id":4,"Name":"Bank of America"},
          {"Id":5,"Name":"RBS Bank"},
          {"Id":6,"Name":"Citi Bank"},
          {"Id":7,"Name":"Barclays Bank"},
          {"Id":8,"Name":"DBS Bank"}];
    });
</script>

</body>
</html>

Results :
See the live result - https://www.w3schools.com/code/tryit.asp?filename=G84O85GKPQR7

List of Banks:
1. ICICI Bank
2. HDFC Bank
3. HSBC Bank
4. Bank of America
5. RBS Bank
6. Citi Bank
7. Barclays Bank
8. DBS Bank

ng-repeat with $first :
1. ICICI Bank

ng-repeat with $middle :
2. HDFC Bank
3. HSBC Bank
4. Bank of America
5. RBS Bank
6. Citi Bank
7. Barclays Bank

ng-repeat with $last :
8. DBS Bank

ng-repeat with $index and $even :
0. ICICI Bank
2. HSBC Bank
4. RBS Bank
6. Barclays Bank

ng-repeat with $index and $odd :
1. HDFC Bank
3. Bank of America
5. Citi Bank
7. DBS Bank