-1

The normal way of learning ng-repeat is as follows

<li ng-repeat="item in items">{{item.attribute}}</li>

and you would have a controller such as

app.controller('myCtrl', function($scope) {
     $scope.items = [
          { name : kitten, attribute : value },
          { name : puppy, attribute : value }
     ];
});

This is good and all, but it gets clunky when I get deeper into my app and have to reference items by their array index. A function that modify's kitten's attribute will go:

$scope.items[0].attribute = value;

I would much rather have:

app.controller('myCtrl', function($scope) {
     $scope.items = {
          'kitten' : {attribute : value },
          'puppy' : { attribute : value }
     };
});

so that I can

$scope.items.kitten.attribute = NEW
-or-
$scope.items["kitten"].attribute = NEW
(are these equivalent??  I think so)

But then how would I loop through them?

<li ng-repeat="item in items">{{item.attribute}}</li>

does not work.

  • In addition to tymeJV's answer, please take the habit always to check [the documentation](http://docs.angularjs.org/api/ng.directive:ngRepeat). All the answers are there. – Blackhole May 16 '14 at 18:54
  • The documentation is cryptic. Answers here are always helpful. Im new to Angular. Please take back your DV. – user3641212 May 16 '14 at 18:58

1 Answers1

2

You can use the following syntax:

ng-repeat="(k, v) in o"

k is the key of the property iterated over, v is the value, and o is the object being iterated.

tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • I knew you'd answer this one. – dckuehn May 16 '14 at 18:05
  • @dckuehn - Just got back from lunch :D – tymeJV May 16 '14 at 18:06
  • so would it be (name, attribute) in o? What if I had different attributes and didn't want to sepcify each one specifically (name, attr1, attr2, ...) in o – user3641212 May 16 '14 at 18:33
  • if you want the cat name then it will be
  • {{key}}
  • if you want those other attribute value it will just simpley be
  • {{values.attribute}}
  • if you have nested attribution u will get values.attribute.xxx.yyy – cjmling May 16 '14 at 18:41