【问题标题】:How do I keep track of the cumulative index in 2 nested ng-repeats如何跟踪 2 个嵌套 ng-repeats 中的累积索引
【发布时间】:2014-01-03 08:31:57
【问题描述】:

从指令的角度来看,我有两个 ng-repeats。 该指令构建一个表格,每个表格单元格的数据来自另一个数据源。 这个数据源需要两个中继器的累积索引。

selectedKandidaat.AntwoordenLijst[$index].Value

我只有当前的 $index,或者 $parent.$index。因此,为了跟踪我想在 Antwoordenlijst[$index] 中使用的总体索引,我需要跟踪一个索引变量。我可以在视图中使用创建和更新索引变量吗?

类似这样的:

..
  {{ 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>

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    每个 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 计算当前索引,但它仅适用于具有相同项目计数的集合。

    【讨论】:

    • 感谢您的回答。但是我需要循环中的总计数来检索 AntwoordenLijst 数组中的值。它需要在渲染选择输入时进行更新。
    • 我想你可以在渲染过程中使用 totalCount 属性。还是你有问题?
    • 我已经尝试过了,但总计数在 ng-repeat 重新加载之间不断累积。有什么建议吗?
    猜你喜欢
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 2017-07-25
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 2015-09-27
    相关资源
    最近更新 更多