在指令 View 中我有两个 ng-repeats。 该指令构建一个表,每个表单元格的数据来自另一个数据源。 该数据源需要两个中继器的累积索引。
selectedKandidaat.AntwoordenLijst[$index].Value
我只有当前的 $index,或者 $parent.$index。因此,为了跟踪我想在 Antwoordenlijst[$index] 中使用的整体索引,我需要跟踪一个索引变量。我可以只在 View 中使用创建和更新索引变量吗?
像这样:
..
{{ totalIndex = 0 }}
<tr ng-repeat="opgave in opgaven">
<td ng-repeat="item in opgave.Items">
{{ totalIndex += 1 }}
..
实际代码
<table class="table">
<tr ng-repeat="opgave in opgaven">
<td ng-repeat="item in opgave.Items">
<select ng-model="selectedKandidaat.AntwoordenLijst[$index].Value"
ng-options="alternatief for alternatief in item.Alternatieven">
</select>
</td>
</tr>
</table>
最佳答案
每个 ng-repeat 创建它自己的范围,因此要找到您需要在父范围中计数的总计数。
<div ng-repeat="a in items1">
parent: {{$index}}
<div ng-repeat="b in items2" itemcell>
child: {{$index}}
total: {{totalCount}}
</div>
</div>
total: {{totalCount}}
并在新的 itemcell
指令中计数器
app.directives
.directive('itemcell', function () {
return {
restrict: 'A',
link: function ($scope, iElement, iAttrs) {
if (!$scope.$parent.$parent.totalCount) {
$scope.$parent.$parent.totalCount = 0;
}
$scope.$parent.$parent.totalCount++;
}
}
})
您也可以尝试通过 $parent.$index 计算当前索引,但只有当您的集合具有相同的项目计数时它才有效。
关于javascript - 如何跟踪 2 个嵌套的 ng-repeats 中的累积索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20899574/