我在控制器中有scope.candidates变量,并使用ng-repeat在我的视图表单中显示数据。我的问题是表中显示的所有对象都不应该。如何仅在表格中显示vicePresidents对象?以下是我的代码。
controller.js
$scope.alertMe = function (candidateGroup) {
alert(candidateGroup);
};
$scope.candidates = {
presidents : [
{
no:1,
name:'Brooke Jovi Jon',
votes:51,
},
{
no:2,
name:'Cabug-os Jerry',
votes:23
},
{
no:3,
name:'Hoorane Nialle',
votes:25
}
],
vicePresidents : [
{
no:11,
name: 'Frank Joemar Timbang',
votes:20
},
{
no:12,
name: 'Curtis Zaymond',
votes:19
},
{
no:13,
name: 'Reeves Manny',
votes:21
}
]
};
view.html
<tbody ng-repeat="candidateGroup in candidates">
<tr ng-repeat="candidate in candidateGroup">
<td>{{candidate.no}} {{candidate.name}}</td>
<td><button ng-click="alertMe($parent.$index)">Alert me!</button></td>
</tr>
答案 0 :(得分:2)
你可以这样做。我猜你只想显示副总统数据。
<tbody ng-repeat="candidateGroup in candidates.vicePresidents">
<tr ng-repeat="candidate in candidateGroup">
<td>{{candidate.no}} {{candidate.name}}</td>
<td><button ng-click="alertMe($parent.$index)">Alert me!</button></td>
</tr>
OR,
<tbody ng-repeat="candidateGroup.vicePresidents in candidates">
<tr ng-repeat="candidate in candidateGroup">
<td>{{candidateGroup.vicePresidents.no}} {{candidateGroup.vicePresidents.name}}</td>
<td><button ng-click="alertMe($parent.$index)">Alert me!</button></td>
</tr>
答案 1 :(得分:2)
因为您希望索引为vicePresidents
,所以必须使用ng-repeat,如下所示:
<table ng-repeat="item in candidates track by $index" ng-if="$index != 0">
<tr ng-repeat="candidate in candidates.vicePresidents">
<td>{{candidate.no}} {{candidate.name}}</td>
<td><button ng-click="alertMe($parent.$index)">Alert me!</button></td>
</tr>
</table>
现在提醒工作了!
因为您的$ parent是由ng-repeat="item in candidates track by $index"
修改强>
更动态地执行此操作是更新后的代码:
<table ng-repeat="item in candidates track by $index" ng-if="item == candidates.presidents">
<tr ng-repeat="candidate in candidates.presidents">
<td>{{candidate.no}} {{candidate.name}}</td>
<td><button ng-click="alertMe($parent.$index)">Alert me!</button></td>
</tr>
</table>
我刚刚更改了ng-if条件。
她是更新的plunker: