MrKlein
MrKlein

Reputation: 127

How do I keep track of the cumulative index in 2 nested ng-repeats

In the view of a directive I have two ng-repeats. This directive builds a table, and the data of every table cell is from another datasource. This datasource needs the cumulative index of the two repeaters.

selectedKandidaat.AntwoordenLijst[$index].Value

I only have got the current $index, or the $parent.$index. So to keep track of the overall index that I want to use in Antwoordenlijst[$index] I will need to keep track of an index variable. Can I just use create and update an index variable in the view.

Something like this:

..
  {{ totalIndex = 0 }}
  <tr ng-repeat="opgave in opgaven">
    <td ng-repeat="item in opgave.Items">
    {{ totalIndex += 1 }}
..

The actual code

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

Upvotes: 4

Views: 507

Answers (1)

IgorCh
IgorCh

Reputation: 2661

Each ng-repeat creates it's own scope, so to find the total count you need count in the parent scope.

<div ng-repeat="a in items1">
    parent: {{$index}}
    <div ng-repeat="b in items2" itemcell>
        child: {{$index}}
        total: {{totalCount}}
    </div>
</div>
total: {{totalCount}}

and counter in new itemcell derective

    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++;
        }
    }
    })

You also can try to count current index via $parent.$index, but it works only if you have collections with the same items count.

Upvotes: 3

Related Questions