如何使用ng-repeat迭代对象内的对象

时间:2016-04-06 02:36:40

标签: angularjs angularjs-ng-repeat

我有一组看起来像这样的对象:

[{
  "mainObj": "main1",
  "subObjArray":{
                 "subObj": "sub1",
                 "deepSubObjArray":[{
                                     "deepSubObj": "deep1",
                                     "property": "something",
                                     },{
                                     "deepSubObj": "deep2",
                                     "property": "somethingElse"
                                   }]
               },
  },{
  "mainObj": "main2",
  "subObjArray":{
                 "subObj": "sub2",
                 "deepSubObjArray":[{
                                     "deepSubObj": "deep3",
                                     "property": "something",
                                     },{
                                     "deepSubObj": "deep4",
                                     "property": "somethingElse"
                                   }]
               },
}]

如果我使用:

<tr ng-repeat="mainObj in mainObjArray">
<td>{{mainObj}}</td>
<td>{{mainObj.subObjArray.deepSubObjArray}}</td>

我得到整个对象字符串和&#34; deepSubObj&#34;字符串按预期,但如果我尝试:

<tr ng-repeat="mainObj in mainObjArray">
<div ng-repeat="deepSubObj in mainObj.subObjArray.deepSubObjArray">
<td>{{deepSubObj}}</td>
</div></tr>

我一无所获。

这不是迭代该数组的正确方法吗?还有什么可能是错的?

2 个答案:

答案 0 :(得分:2)

的HTML

<div ng-controller="MyCtrl">
    <ul>
        <li ng-repeat="mainObj in mainObjArray">
            {{mainObj.mainObj}}
            <ul>
                <li ng-repeat="deepSubObj in mainObj.subObjArray.deepSubObjArray">
                    {{deepSubObj.deepSubObj}}
                </li>
            </ul>
        </li>
    </ul>
</div>

JS

angular.module('myApp', [])
        .controller('MyCtrl', function ($scope) {
            $scope.mainObjArray = [{
                "mainObj": "main1",
                "subObjArray": {
                    "subObj": "sub1",
                    "deepSubObjArray": [{
                        "deepSubObj": "deep1",
                        "property": "something",
                    }, {
                        "deepSubObj": "deep2",
                        "property": "somethingElse"
                    }]
                },
            }, {
                "mainObj": "main2",
                "subObjArray": {
                    "subObj": "sub2",
                    "deepSubObjArray": [{
                        "deepSubObj": "deep3",
                        "property": "something",
                    }, {
                        "deepSubObj": "deep4",
                        "property": "somethingElse"
                    }]
                },
            }]
        });

效果

enter image description here

答案 1 :(得分:1)

嵌套ng-repeat代码时,example card from the Material-UI docs

问题与布局有关,而与ng-repeat迭代无关。 <div>标记之外的表格中不允许使用<td>标记,这会导致表格呈现错误。

使用嵌套的ngRepeat指令可能会对性能有害,具体取决于对象。在输出之前准备数据通常是更好的解决方案。