Jimmery
Jimmery

Reputation: 10139

AngularJS: How do I get the current iteration number in a ng-repeat

I have this ng-repeat loop:

<div ng-repeat="chapter in chapters">
    <div>Chapter #<span>{{ X }}</span>: {{ chapter.name }}</div>
</div>

How do I get {{ X }} to be the iteration in the loop?

To give me a result like this:

Chapter #1: The Beginning

Chapter #2: The Middle

Chapter #3: The End

Upvotes: 1

Views: 3851

Answers (2)

Sajeetharan
Sajeetharan

Reputation: 222582

You can use $index,

var app = angular.module("App", []);
app.controller("Cont", function($scope) {
  var Chapters = [
  {
    "pid": "110",
    "name": "Harry"
   
  },
  {
    "pid": "109",
    "name": "potter"
   
  },
  {
    "pid": "101",
    "name": "Peter"
  
  },
  {
    "pid": "104",
    "name": "Janifer"
    
  }
 
];
  $scope.chapters = Chapters;
});
<!DOCTYPE html>
<html>
<head>
   <script data-require="[email protected]" data-semver="1.4.7" src="https://code.angularjs.org/1.4.7/angular.js"></script>

</head>
<body ng-app="App" ng-controller="Cont">
  
        <div ng-repeat="x in chapters track by $index">
          <td> Chapter#{{$index}} {{x.name}}</td>
          
        </div>
      
  </body>

</html>

Upvotes: 4

mrogers
mrogers

Reputation: 1217

Use the built in $index variable.

https://docs.angularjs.org/api/ng/directive/ngRepeat

Upvotes: 4

Related Questions