如何使用ng-repeat遍历JSON中的数组数组?

梦想家

我正在尝试遍历JSON对象userTypes
对于以下代码:

在第一个ng-repeat中:
{{user.type}}输出'Parent'按预期),
{{user.options}}输出'[{“ option1”:“ 11QWERT”,“ option2”:“ 22QWERT”}]''按预期)。

但是在第二个中ng-repeat,我无法遍历user.options和输出每个{{options}}

为了获得option1option2作为第二输出,应该改变什么ng-repeat

JS片段

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

HTML片段

<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>
阿特姆·彼得罗森

将您的孩子替换<li><ul>,然后可以user.options像这样进行迭代

<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>

或者,如果您options可能包含多个对象,则:

<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>

如果不需要对象键:

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

小提琴

扩展说明:

在您的示例中,您<li>在另一个标签内标签<li>

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

由于它不是有效的HTML浏览器,因此会将此标记解释为以下内容:

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

由于ng-repeat为每次迭代创建新的作用域,因此您无法立即访问user变量,ng-repeat并且迭代器也不会运行。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章