How to set the id attribute of a HTML element dynamically with angularjs (1.x)?

How to set the id attribute of a HTML element dynamically with angularjs (1.x)?

Provided an HTML element of type div, how to set the value of its id attribute, which is the concatenation of a scope variable and a string ?


Solution 1:

ngAttr directive can totally be of help here, as introduced in the official documentation

For instance, to set the id attribute value of a div element, so that it contains an index, a view fragment might contain

<div ng-attr-id="{{ 'object-' + myScopeObject.index }}"></div>

which would get interpolated to

<div id="object-1"></div>

Solution 2:

This thing worked for me pretty well:

<div id="{{ 'object-' + $index }}"></div>

Solution 3:

A more elegant way I found to achieve this behaviour is simply:

<div id="{{ 'object-' + myScopeObject.index }}"></div>

For my implementation I wanted each input element in a ng-repeat to each have a unique id to associate the label with. So for an array of objects contained inside myScopeObjects one could do this:

<div ng-repeat="object in myScopeObject">
    <input id="{{ + 'Checkbox'}}" type="checkbox">
    <label for="{{ + 'Checkbox'}}">{{}}</label>

Being able to generate unique ids on the fly can be pretty useful when dynamically adding content like this.

Related:  How do you import multiple javascript files in HTML index file without the bloat?

Solution 4:

In case you came to this question but related to newer Angular version >= 2.0.

<div [id]=""></div>

Solution 5:

You could just simply do the following

In your js

$ = 0;

In your template

<div id="number-{{$}}"></div>

which will render

<div id="number-0"></div>

It is not necessary to concatenate inside double curly brackets.

Solution 6:

Just <input id="field_name_{{$index}}" />