How to set the id attribute of a HTML element dynamically with angularjs (1.x)?
JavascriptAngularjsAngularjs ScopeString ConcatenationJavascript Problem Overview
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 ?
Javascript Solutions
Solution 1 - Javascript
ngAttr
directive can totally be of help here, as introduced in the official documentation
https://docs.angularjs.org/guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes
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 - Javascript
This thing worked for me pretty well:
<div id="{{ 'object-' + $index }}"></div>
Solution 3 - Javascript
In case you came to this question but related to newer Angular version >= 2.0.
<div [id]="element.id"></div>
Solution 4 - Javascript
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="{{object.name + 'Checkbox'}}" type="checkbox">
<label for="{{object.name + 'Checkbox'}}">{{object.name}}</label>
</div>
Being able to generate unique ids on the fly can be pretty useful when dynamically adding content like this.
Solution 5 - Javascript
You could just simply do the following
In your js
$scope.id = 0;
In your template
<div id="number-{{$scope.id}}"></div>
which will render
<div id="number-0"></div>
It is not necessary to concatenate inside double curly brackets.
Solution 6 - Javascript
Just <input id="field_name_{{$index}}" />
Solution 7 - Javascript
If you use this syntax:
<div ng-attr-id="{{ 'object-' + myScopeObject.index }}"></div>
Angular will render something like:
<div ng-id="object-1"></div>
However this syntax:
<div id="{{ 'object-' + $index }}"></div>
will generate something like:
<div id="object-1"></div>