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)? angularjs angularjs

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


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>


This thing worked for me pretty well:

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


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

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