dreamer dreamer - 2 months ago 11
JSON Question

How to iterate through an array of arrays in JSON using ng-repeat?

I am trying to iterate over a JSON object

userTypes
.

For the below code:


In the 1st ng-repeat:

{{user.type}}
outputs 'Parent'(as expected),

{{user.options}}
outputs '[{"option1":"11QWERT","option2":"22QWERT"}]'(as expected).


But in the 2nd
ng-repeat
, I am not able to iterate through the
user.options
and output each of the
{{options}}



What should be changed to get the
option1
and
option2
as the outputs in 2nd
ng-repeat
?

JS snippet

var userTypes = [{
"type": 'Parent',
"options": [{
"option1": "11QWERT",
"option2": "22QWERT"
}]
}]


HTML snippet

<li ng-repeat="user in userTypes">
<p>{{user.type}}</p>
<p>{{user.options}}</p>
<li ng-repeat="option in user.options">
<p>
{{option}}
</p>
</li>
</li>

Answer

Replace your child <li> with <ul> and then you can iterate user.options like so:

<li ng-repeat="user in userTypes">
    <p>{{user.type}}</p>
    <ul ng-repeat="(key, value) in user.options[0]">
        <p>{{key}}: {{value}}</p>
    </ul>
</li>

Or if your options may include more then one object:

<li ng-repeat="user in userTypes">
    <p>{{user.type}}</p>
    <ul ng-repeat="option in user.options">
        <li ng-repeat="(key, value) in option">{{key}}: {{value}}</li>
    </ul>
</li>

If you don't need object keys:

<ul ng-repeat="option in user.options">
    <li ng-repeat="item in option">{{item}}</li>
</ul>

Fiddle

Extended explanation:

In your example you have <li> tag inside another <li>:

<li ng-repeat="user in userTypes">
    <li ng-repeat="option in user.options">
    </li>
</li>

Since it is not a valid HTML browser will interprets this markup to following:

<li ng-repeat="user in userTypes">
</li>
<li ng-repeat="option in user.options">
</li>

Since ng-repeat creates new scope for each iteration you can't access user variable in second ng-repeat and iterator wouldn't run.