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 ?
7 Answers
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>
8 Comments
myScopeObject come from? Where would I define it?myScopeObject is a property of a scope object exposed using a controller. Please see also docs.angularjs.org/guide/controller. Is that clear enough for you or shall I elaborate further?<div id="{{ 'object' + index }}"> and <div ng-attr-id="{{ 'object' + index }}"> ? The docs seem to say prepending ng-attr- is to help out for cases where the element is something non-standard, like not a <div>. Am I reading the docs right?This thing worked for me pretty well:
<div id="{{ 'object-' + $index }}"></div>
3 Comments
ng-attr-id method is to ensure that the raw ng expression is never rendered in a valid HTML attribute (e.g. id, label, etc). This is to stop any downstream usage reading ng 'junk' (e.g. before render is complete, or after a js crash)In case you came to this question but related to newer Angular version >= 2.0.
<div [id]="element.id"></div>
5 Comments
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.
2 Comments
Just <input id="field_name_{{$index}}" />
3 Comments
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>