Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 730
dreamer Avatar asked May 04 '15 13:05

dreamer


2 Answers

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.

like image 148
Artem Petrosian Avatar answered Sep 20 '22 11:09

Artem Petrosian


For this exact JSON input it should be like this:

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

However as you said you want non fixed number of options, update your JSON to be like this:

"options":["11QWERT","22QWERT"]

And then your code should work as you wanted it.

You can add each new element to list with simple coma before it.

like image 40
nikola-miljkovic Avatar answered Sep 18 '22 11:09

nikola-miljkovic