Subha
Subha

Reputation: 761

angularjs - ng repeat with json

how can i use ng-repeat for below json

$scope.prlists = {
  "1": [{
    "id": "1",
    "name": "One",
    "qty": 2,
    "amount": "1.00",
    "cat": "1.00"
  }],
  "3": [{
    "id": "3",
    "name": "backit",
    "qty": 3,
    "amount": "2.00",
    "cat": "2.00"
  }]
}
<div ng-repeat="pro in prlists">
  name : pro.name
</div>

can not able to get the name due to inner array. How to solve

Upvotes: 1

Views: 55

Answers (2)

Daniel
Daniel

Reputation: 1087

ngRepeat can iterate over object properties. So, you can do something like

<div ng-repeat="(key, pro) in prlists">
    name: {{pro[0].name}}
</div>

See the documentation at: https://docs.angularjs.org/api/ng/directive/ngRepeat

Note that this will not guarantee the order in Angular version >= 1.4, since it will depend on the browser's ordering. You might be able to sort it using the orderBy filter

<div ng-repeat="(key, pro) in prlists | orderBy:key">
    name: {{pro[0].name}}
</div>

See: https://docs.angularjs.org/api/ng/filter/orderBy

If the inner arrays are not just a single element, you may have to nest a second ngRepeat inside the first div.

Upvotes: 2

Rajesh
Rajesh

Reputation: 24955

As I have already commented:

try pro[0].name

Reason:

In you code, for every iteration, $data(pro) will have

[{
  "id": "1",
  "name": "One",
  "qty": 2,
  "amount": "1.00",
  "cat": "1.00"
}]

Now as you see, this is not an object, so you have to go to its first and only child. Also you are missing {{}}. name : pro.name this will print pro.name as text and not parse it.

Working demo.

Upvotes: 1

Related Questions