Eric Hannum Eric Hannum - 5 months ago 16
AngularJS Question

How do I get the $index of element in an ng-repeat when repeating over an object?

I know object values don't have indexes but say I have an object named foo with 5 keys and I do:

<div ng-repeat="(key,value) in foo">


I will end up with 5 divs on my page.

My question is how do I ask Angular, "Hey, which div is this? Is it the first one? Is it the second one? Give me a number please." I can't use
{{$index}}
because objects don't have indexes. I can't use
{{$id}}
because it seems to give a number that starts from 5 and is always odd... sometimes. I just want to know where in the
ng-repeat
I am when repeating over an object and not an array.

Answer

You could still use {{$index}} when repeating non array objects.

Markup:

<div ng-app>
  <div ng-controller="testCtrl">
    <div ng-repeat="(key, value) in data">
      <span>{{$index}} -</span>
      <span>{{key}} -</span>
      <span>{{value}}</span>
    </div>
  </div>
</div>

Controller

function testCtrl($scope) {

  $scope.data = {
    prop1: 'a',
    prop2: 'b',
    prop3: 'c',
    prop4: 'c'
  }

}

Output:

0 - prop1 - a
1 - prop2 - b
2 - prop3 - c
3 - prop4 - c

See this fiddle for your reference