Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 322
Thierry Marianne Avatar asked May 14 '14 12:05

Thierry Marianne


People also ask

How do I enable id attributes for elements?

In your project settings, under General, make sure "Expose the option to add an ID attribute to HTML elements" is enabled.

What is the use of the html5 id attribute?

The id global attribute defines an identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS).


2 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> 
like image 148
Thierry Marianne Avatar answered Oct 27 '22 00:10

Thierry Marianne


This thing worked for me pretty well:

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

like image 22
Tanveer Shaikh Avatar answered Oct 27 '22 01:10

Tanveer Shaikh