在嵌套的ng-repeat中通过$index跟踪的最佳方法是什么?

What would be the best way to track by $index in nested ng-repeat?

本文关键字:最佳 跟踪 方法 是什么 index ng-repeat 嵌套      更新时间:2023-09-26

我有以下HTML:

<div class="row" ng-repeat="row in grid track by $index">
    <div cell class="cell" ng-repeat="cell in row track by $index" ng-click="game.addItem($index, $index)">
        {{cell.value}}
    </div>
</div>

我需要在第一个ng-repeat和第二个ng-repeat中按索引跟踪,以便将它们传递给addItem()。通过这两项考试的最好方法是什么?

我相信你能做到:

<div class="row" 
     ng-repeat="row in grid track by $index" 
     ng-init="$rowIndex = $index">
  <div cell class="cell" 
       ng-repeat="cell in row track by $index" 
       ng-click="game.addItem($rowIndex, $index)">
    {{cell.value}}
  </div>
</div>

(Init可能需要放在外部div上,因为我坐在这里记不清了)

尽管问题来了,为什么不能直接使用单元格和行呢?为什么需要索引呢?

<div class="row" ng-repeat="row in grid track by $index">
    <div cell class="cell" ng-repeat="cell in row track by $index" 
       ng-click="game.addItem(row, cell)">
        {{cell.value}}
    </div>
</div>