Peter Warbo
Peter Warbo

Reputation: 11700

AngularJS increment value for id attributes

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!

Upvotes: 5

Views: 7443

Answers (2)

Paul Boutes
Paul Boutes

Reputation: 3315

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

Upvotes: 1

Can Guney Aksakalli
Can Guney Aksakalli

Reputation: 1330

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>

Upvotes: 1

Related Questions