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 ?
This question is related to
javascript
angularjs
angularjs-scope
string-concatenation
In case you came to this question but related to newer Angular version >= 2.0.
<div [id]="element.id"></div>
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.
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>
Just <input id="field_name_{{$index}}" />
This thing worked for me pretty well:
<div id="{{ 'object-' + $index }}"></div>
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.
Source: Stackoverflow.com