我正在尝试遍历JSON对象userTypes
。
对于以下代码:
在第一个ng-repeat中:
{{user.type}}
输出'Parent'(按预期),
{{user.options}}
输出'[{“ option1”:“ 11QWERT”,“ option2”:“ 22QWERT”}]''(按预期)。
但是在第二个中ng-repeat
,我无法遍历user.options
和输出每个{{options}}
为了获得option1
和option2
作为第二输出,应该改变什么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] 删除。
我来说两句