【问题标题】:AngularJS Count within nested ng-repeat嵌套的 ng-repeat 中的 AngularJS 计数
【发布时间】:2015-11-29 07:52:43
【问题描述】:

我正在寻找一种方法来计算循环中创建的“td”元素的数量。

我不能为此使用$index,因为在每一行上索引都会被重置,在每次迭代中设置 i 的最干净和最简单的方法是什么。所以第一列值为 1,第一列计数为 0。

到目前为止我的代码:

        <table class="calendar">
            <thead>
                <tr>
                    <th>M</th>
                    <th>T</th>
                    <th>W</th>
                    <th>T</th>
                    <th>F</th>
                    <th>S</th>
                    <th>S</th>
                </tr>
            </thead>
            <tbody ng-click="bindCellValue($event)">
                <tr ng-repeat="week in (days.length/7 | array)">
                    <td ng-repeat="day in days.slice(7*$index, 7*$index + 7) track by $index">
                        {{ day }}
                        <i class="icon ion-checkmark answer-correct" ng-if="submitted && answers[i].correct"></i>
                        <i class="icon ion-close answer-wrong" ng-if="submitted && !answers[i].correct"></i>
                    </td>
                </tr>

            </tbody>
        </table>

在我的控制器中:

$scope.days = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, null, null, null, null ];

【问题讨论】:

  • 你的意思是days.length?无论如何,你事先知道号码。它是基于模型的,所以为什么要计算一些东西呢?
  • 因为我需要使用项目的计数来匹配答案数组中的键:ng-if="submitted && answers[i].correct">
  • 你可以为它创建一个 plunker 或 jsfiddle 吗?
  • 我不太确定我得到了这个问题。你想要每个单元格的当前计数吗?您能否绘制或制作一张关于您希望它如何运作的快速静态表格?
  • 每个 ng-repeat 使用传递的数据创建一个子作用域,并在该作用域中添加一个额外的 $index 变量。所以你需要做的是到达父作用域,并使用它$索引。见this

标签: javascript angularjs angularjs-ng-repeat


【解决方案1】:

您可以使用ng-init

<tr ng-repeat="week in (days.length/7 | array)" ng-init="w = $index">
    <td ng-repeat="day in days.slice(7*$index, 7*$index + 7) track by $index" ng-init="i = w*7 + $index">
        {{ day }}
        <i class="icon ion-checkmark answer-correct" ng-if="submitted && answers[i].correct"></i>
        <i class="icon ion-close answer-wrong" ng-if="submitted && !answers[i].correct"></i>
    </td>
 </tr>

【讨论】:

    【解决方案2】:

    应该是这样的:

    <i class="icon ion-checkmark answer-correct" ng-if="submitted && answers[$parent.$parent.$index * 7 + $parent.$index].correct"></i>
    

    基本上,将 $parents 索引(您创建一周的索引)乘以 7,然后将另一个 $index 添加进去。我建议将其输出,直到您确定它是正确的。

    【讨论】:

    • ng-if 创建一个新范围。那么,您认为$parent 指向哪里?
    • 啊,是的,只是掩盖了这一点,所以加倍 $parent
    猜你喜欢
    • 2018-01-26
    • 2018-12-23
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多