最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJS increment value for id attributes - Stack Overflow

programmeradmin1浏览0评论

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!

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!

Share Improve this question asked Aug 3, 2015 at 9:04 Peter WarboPeter Warbo 11.8k15 gold badges104 silver badges201 bronze badges 1
  • Can you show an example? – Endre Simo Commented Aug 3, 2015 at 9:06
Add a ment  | 

2 Answers 2

Reset to default 1

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

发布评论

评论列表(0)

  1. 暂无评论