Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 970
Peter Warbo Avatar asked Oct 31 '22 22:10

Peter Warbo


2 Answers

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>
like image 52
Can Guney Aksakalli Avatar answered Nov 11 '22 14:11

Can Guney Aksakalli


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

like image 28
Paul Boutes Avatar answered Nov 11 '22 12:11

Paul Boutes