Hoa Hoa - 1 year ago 68
AngularJS Question

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

The documentation:


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 Source

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.


        <tr ng-repeat="person in object">

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>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download