Home » Angularjs » How to set the id attribute of a HTML element dynamically with angularjs?

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

Posted by: admin November 2, 2017 Leave a comment

Questions:

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 ?

Answers:

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>

Questions:
Answers:

This thing worked for me pretty well:

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

Questions:
Answers:

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.

Questions:
Answers:

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.

Questions:
Answers:

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>