0

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)

2
  • The index is sequential numeric. You just asking, how to iterate over an object? Does your object has numeric indexes ? Commented Jul 15, 2014 at 5:28
  • No I've been 'forced' to use an object since using an array is not binding my variables properly. So I'm wondering if there's a way to loop over it as if it were an array using AngularJS syntax. Commented Jul 15, 2014 at 5:31

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

Comments

1

you can $index in ngRepeat iteration. See below fiddle.

http://jsfiddle.net/NFNvc/24/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.