AngularJs-嵌套ng-repeat

时间:2018-09-19 16:18:32

标签: angularjs nested angularjs-ng-repeat

我正在尝试遍历给定的JSONObject,该对象中包含JSONArray并以html显示。因此,这是示例:

jsonData:

{
    "category1": [
        {
            "name": "Some title",
            "desc": "And its description"
        },
        {
            "name": "Another title here",
            "desc": "Also description here"
        }
    ],
    "category2": [
        {
            "name": "Dummy name",
            "desc": "Lorem ipsum etc."
        }
    ],
    "category3": [
        {
            "name": "Blah",  
            "desc": "Blah blah"
        }
    ]
}

HTML:

<div ng-repeat="category in vm.jsonData track by $index">
    <h3>{{ category }}</h3>
    <ul>
        <li ng-repeat="item in category">
            <span><b>{{ item.name }}</b></span><br/>
            <span>{{ item.desc }}</span>
        </li>
    </ul>
</div>

到目前为止,我可以正确获得namedesc,但是我错过了HTML中的category。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:3)

您需要ng-repeat作为<div ng-repeat="(key, value) in vm.jsonData track by $index">

演示

var app = angular.module('testApp',[]);
app.controller('testCtrl',function(){
  this.jsonData = {
    "category1": [
        {
            "name": "Some title",
            "desc": "And its description"
        },
        {
            "name": "Another title here",
            "desc": "Also description here"
        }
    ],
    "category2": [
        {
            "name": "Dummy name",
            "desc": "Lorem ipsum etc."
        }
    ],
    "category3": [
        {
            "name": "Blah",  
            "desc": "Blah blah"
        }
    ]
};

 vm = this;

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="testApp" ng-controller="testCtrl as vm">
<div ng-repeat="(key, value) in vm.jsonData track by $index">       
    <ul>    
     {{key}} 
        <li ng-repeat="item in value">
            <span>{{ item.name }}</span>
            <span>{{ item.desc }}</span>
        </li>
    </ul>
</div>
</body>

答案 1 :(得分:1)

在您的情况下,您需要访问元素“ category1”的键。

您可以使用此语法

ng-repeat="(key, value) in data"

here working jsfiffle for your example