GeeWhizBang
GeeWhizBang

Reputation: 857

How to create unique `id` attributes in AngularJS ng-repeat repeaters

I'm seeing this in our templates. They say it's so the code can be tested but it still seems wrong to me:

<tr ng-repeat="comp in collection">
    <td>
        <span id="someId">{{comp.someText}}</span>
    </td> 
    ....

I'm thinking we should be using name instead.

Upvotes: 2

Views: 1239

Answers (1)

JC Ford
JC Ford

Reputation: 7066

If you really need unique IDs inside the repeater, try this:

<tr ng-repeat="comp in collection">
    <td>
        <span id="someId{{$index}}">{{comp.someText}}</span>
    </td>

So if, for instance, you need to link labels to inputs in the ngRepeat:

<tr ng-repeat="comp in collection">
    <td>
        <label for="field{{$index}}">{{field.label}}</label>
        <input type="text" id="field{{$index}}" ng-model="field.value" />
    </td>

This approach is especially useful if you need to have check boxes with clickable labels inside the ngRepeat.

Upvotes: 4

Related Questions