我的JSON看起来像这样:
{
"contact-info": {
"phonebook": [
{
"name": "John Snow",
"phones": [
{
"phone": "home",
"number": "1234"
}
],
"nick": "bastard"
},
{
"name": "Arya Stark",
"phones": [
{
"phone": "cell",
"number": "234"
},
{
"phone": "work",
"number": "345"
},
{
"phone": "home",
"number": "456"
}
],
"nick": "no one"
},
{
"name": "Theon",
"phones": [
{
"phone": "fax",
"number": "567"
}
],
"nick": "Reek"
},
{
"name": "Aemon",
"phones": [
{}
],
"nick": "maester"
}
]
}
}
到目前为止,由于我对Angular的了解有限,我只能打印每个名字的第一个数字:
tbody
tr( ng-repeat="person in JSON.contact-info.phonebook")
td {{person.name}}
td {{person.phone[0].phone}}
td {{person.phone[0].number}}
td {{person.nick}}
每次我想为手机部分创建嵌套的ng-repeat时,我都会遇到错误。应该怎么做?
谢谢
答案 0 :(得分:1)
你不能用一个ng-repeat
来做你需要做嵌套重复,一个跨人,然后跨人民电话。
问题是你需要迭代两次并仍然产生表行。有两件事可以帮助你重复启动ng-repeat-end指令,你可以将指令放在注释中。
tbody
// ng-repeat-start='person in JSON.JSON.contact-info.phonebook'
tr(ng-repeat='phone in person.phone')
td {{ person.name }}
td {{ phone.phone }}
td {{ phone.number }}
td {{ person.nick }}
// ng-repeat-end
您最终会获得此标记:
<table>
<tbody>
<!-- ng-repeat-start='person in JSON.JSON.contact-info.phonebook'-->
<tr ng-repeat="phone in person.phone">
<td>{{ person.name }}</td>
<td>{{ phone.phone }}</td>
<td>{{ phone.number }}</td>
<td>{{ person.nick }}</td>
</tr>
<!-- ng-repeat-end -->
</tbody>
</table>
另一种选择是将原始json转换为一个级别列表并使用简单的重复。
var allPhones = []
_.each(json, (p) =>{ _.each(p.phone, (ph) => allPhones.push({
name: p.name,
phone: ph.phone,
number: ph.number,
nick: p.nick})
})
处理角侧的简单ng-repeat
答案 1 :(得分:1)
试试这个。
var app = angular.module("app",[]);
app.controller("ctrl" , function($scope){
$scope.items = {
"contact-info": {
"phonebook": [
{
"name": "John Snow",
"phones": [
{
"phone": "home",
"number": "1234"
}
],
"nick": "bastard"
},
{
"name": "Arya Stark",
"phones": [
{
"phone": "cell",
"number": "234"
},
{
"phone": "work",
"number": "345"
},
{
"phone": "home",
"number": "456"
}
],
"nick": "no one"
},
{
"name": "Theon",
"phones": [
{
"phone": "fax",
"number": "567"
}
],
"nick": "Reek"
},
{
"name": "Aemon",
"phones": [
{}
],
"nick": "maester"
}
]
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl" class="panel-group" id="accordion">
<table>
<thead>
<tr>
<td>name</td>
<td>phone</td>
<td>number</td>
<td>nick</td>
</tr>
</thead>
<tbody ng-repeat="(key,value) in items">
<tr ng-repeat="person in value.phonebook">
<td >{{person.name}}</td>
<td ng-repeat="phone in person.phones">{{phone.phone}}{{phone.number}}</td>
<td >{{person.nick}}</td>
</tr>
</tbody>
</table>
</div>