Hoa Hoa - 5 months ago 15
AngularJS Question

In AngularJS, how can I loop through an object using ng-repeat with a numeric index?

The documentation:

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

says that $index will be a key if I am iterating through an object. How do I retrieve a sequential numeric index (0,1,2...) instead? (Assuming I still wish to use an object and not an array)

Answer

Consider your object is

$scope.object = {};
$scope.object.person1 = {name: "tom", age:"5"};
$scope.object.person2 = {name: "jerry", age: "5"};
$scope.object.person3 = {name: "sparky", age: "3"};

Now you want to display the people in the object in a table.

<table>
    <thead>
        <th>Id</th>
        <th>Name</th>
        <th>Age</th>
    </thead>

    <tbody>
        <tr ng-repeat="person in object">
            <td>{{$index+1}}</td>
            <td>{{person.name}}</td>
            <td>{{person.age}}</td>
        </tr>
    </tbody>
</table>

your result would be

Id Name   Age
1  tom    5
2  jerry  5
3  sparky 3

sometimes you may run into Duplicates error [ngRepeat:Dupes] using ng-repeat. The error occurs when you have duplicate entries in your array. For example

$scope.store = ["apple", "milk", "carrots", "apple"];
<li ng-repeat="item in store">{{item}}</li>

apple occurs twice, so its a duplicate. You can read more about the error at https://docs.angularjs.org/error/ngRepeat/dupes

In order to avoid the error you tell ng-repeat to use the $index to track the elements in the array by numeric indices which will always be unique.

<li ng-repeat="item in store track by $index">{{item}}</li>