Thierry Marianne Thierry Marianne - 3 months ago 25
AngularJS Question

How to set the id attribute of a HTML element dynamically with angular js?

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 ?

Answer

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

https://docs.angularjs.org/guide/directive#-ngattr-attribute-bindings
Update: documentation moved to: 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>
Comments