I have some html that looks like this:
<tr ng-repeat="x in y">
<td>
<div ng-attr-id="{{getId()}}"></div>
</td>
<td>
<div ng-attr-id="{{getId()}}"></div>
</td>
<td>
<div ng-attr-id="{{getId()}}"></div>
</td>
</tr>
I want to have an id that starts from 1 for the first <td>
element and then increments one for each <td>
element.
By doing in the controller:
$scope.getId = function () {
counter++;
return counter;
}
I get
10 $digest() iterations reached. Aborting!
You can use $index for this:
<tr ng-repeat="x in y track by $index">
<td>
<div ng-attr-id="{{$index + 1}}"></div>
</td>
</tr>
For nested loops you can define a new track value and combine with $index
or for static three elements you can write this:
<tr ng-repeat="x in y track by $index">
<td>
<div ng-attr-id="{{$index*3 + 1}}"></div>
</td>
<td>
<div ng-attr-id="{{$index*3 + 2}}"></div>
</td>
<td>
<div ng-attr-id="{{$index*3 + 3}}"></div>
</td>
</tr>
You can use $index
variable of ngRepeat
directive.
$index
: iterator offset of the repeated element (0..length-1)ngRepeat
So, you can do :
<div ng-attr-id="{{$index + 1}}"></div>
We use $index + 1
to start from 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With