0

Docs: https://code.angularjs.org/1.2.26/docs/api/ng/directive/ngRepeat

The ngRepeat directive instantiates a template once per item from a collection. Each template instance gets its own scope, where the given loop variable is set to the current collection item, and $index is set to the item index or key.

It seems like I'm getting the index not the key.


Controller:

$scope.items = {
  "key1" : "val1",
  "key2" : "val2"
};

View:

<div class="item" ng-repeat="item in items">{{ $index }} {{item}}</div>

Result:

0 val1
1 val2

http://plnkr.co/edit/0g9EL6kqYcm4jNpdDZ9L?p=preview

I'd like to display key, which in this case should be key1 and key2. Is there a special syntax for that?

Mars Robertson
  • 12,673
  • 11
  • 68
  • 89

2 Answers2

2

Try

<div class="item" ng-repeat="(key, value) in items">{{ $index }} {{key}} {{value}}</div>
Juho Vepsäläinen
  • 26,573
  • 12
  • 79
  • 105
0

It should be like this:

<div class="item" ng-repeat="(key, val) in items">{{ key }} {{ val }}</div>

Here's the plnkr: http://plnkr.co/edit/nWqK8rFVaKzzEpbAuqdx?p=preview

And here's the corresponding point from the docs:

(key, value) in expression – where key and value can be any user defined identifiers, and expression is the scope expression giving the collection to enumerate.

For example: (name, age) in {'adam':10, 'amalie':12}.

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

Reins
  • 1,109
  • 1
  • 17
  • 35