spez86
spez86

Reputation: 732

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

I have the following 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>

I need to track by index in the first ng-repeat and in the second, in order to pass them off to addItem(). What would be the best way to pass both of them?

Upvotes: 5

Views: 4461

Answers (2)

Jens
Jens

Reputation: 3412

I belieive you can do:

<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 might need to go on the outer div, can't recall as I sit here)

Although the question would beg, why can't you just use the cell and row, what do you specifically need the indexes for.

Upvotes: 6

sylwester
sylwester

Reputation: 16498

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

Upvotes: 2

Related Questions