Brandon Shega
Brandon Shega

Reputation: 769

Adding an id to HTML when looping through Angular objects

I have some HTML:

<div class='list-group' >
    <a href="javascript:;" ng-attr-id="{{company.policy_number}}" class='list-group-item' ng-repeat="company in companies">{{company.primary_name}}</a>
</div>

Each object looks like:

{
    policy_number: 12345,
    primary_name: "Policy Name Here"
}

How can I set the id of the link that I create to the policy number of the object?

I have tried both id="{{company.policy_number}} and ng-attr-id={{company.policy_number}}, is there something that I am missing here where I can not access this?

Thanks!

Upvotes: 2

Views: 907

Answers (2)

galets
galets

Reputation: 18472

I don't like it myself, when someone instead of answering the question replies with "why do you even doing that, you should be doing it another way", but nevertheless here I go.

If you are looking to give ID to controls within ng-repeat loop, you are likely doing something wrong. You only need ID if you are accessing DOM, but the whole point of angular is that you should not be accessing DOM. Once you see jquery in your controller, it's time to stop and reevaluate why are you doing it and there's pretty much a guaranteed better way to handle what you want.

For example: if you are looking to provide a click handler it is much better to have something like a ng-click="policy_clicked(company.policy_number)" inside your HTML within a loop

Again, I apologize for giving you a non-answer, but I've seen folks doing this mistake over and over again, and it leads to hugely unsustainable code

Upvotes: 0

Mukund Kumar
Mukund Kumar

Reputation: 23191

You should use id="{{company.policy_number}}".

It is working in this plunker

Upvotes: 2

Related Questions