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

时间:2014-06-26 19:24:58

标签: javascript angularjs angularjs-ng-repeat

我有以下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和第二个中按索引进行跟踪,以便将它们传递给addItem()。通过这两种方式的最佳方式是什么?

2 个答案:

答案 0 :(得分:6)

我相信你能做到:

<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,因为我坐在这里不能回忆起来)

虽然问题会乞求,为什么你不能只使用单元格和行,你特别需要索引。

答案 1 :(得分:2)

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