Explain Codes LogoExplain Codes Logo

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

javascript
angularjs
dynamic-binding
ng-attr
Alex KataevbyAlex Kataev·Feb 21, 2025
TLDR

In AngularJS 1.x, the id attribute can be set dynamically using the ng-attr-id directive along with {{}} interpolation:

<div ng-app="myApp" ng-controller="myCtrl"> <div ng-attr-id="{{elementId}}">Dynamic ID</div> </div>

Whereas in your AngularJS controller:

angular.module('myApp', []).controller('myCtrl', function($scope) { $scope.elementId = 'dynamicIdValue'; // change this to alter your dynamic id });

Here, the id attribute updates in real-time whenever there's a change in $scope.elementId. The ng-attr-id brings dynamic assignment to life, while interpolation performs the binding magic.

Dynamically setting HTML attributes

Consider a typical scenario in which we concatenate scope variable with string using ngAttr for setting HTML attributes. It is just like adding a spice to your code:

<div ng-attr-id="{{variable + '_suffix'}}"></div>

And in your controller:

$scope.variable = 'uniquePart'; /*You can call it 'partOfPie', but make sure it's unique*/

As appetizing as it sounds, the id here will turn out like "uniquePart_suffix". Ensure $scope.variable is set right off the bat to feed into predictable dynamic updates.

Unique IDs in ng-repeat iterations

When handling the ng-repeat directive, be sure to maintain uniqueness in id across DOM elements. Here $index comes to the rescue:

<div ng-repeat="item in items" ng-attr-id="{{'item_' + $index}}"> /* Catch! You've ID here */ </div>

In one stroke, this method rescues from any id conflicts, bringing dynamic content handling to its peak.

Update attributes on-the-go

As dynamism is key in angularJS, your DOM attributes should wear camouflage with the application. A combination of ngAttr and data binding effectively reflects changes to scope through attributes like id:

$scope.updateId = function(newId) { $scope.variable = newId; /*Like a chameleon, change comes from inside*/ };

Changes to $scope.variable magically reflect in your id attribute.

Angular 2+ and dynamic binding

Taking a quick detour to next-gen Angular (2+), the syntax got a face-lift for dynamic binding and became more streamlined:

<!--Angular 2+ syntax--> <div [id]="variable + 'suffix'">/* Enjoy the syntax sugar! */ </div>

Watch out for pitfalls and remember best practices

While setting dynamic ids, ensure you're not stepping into common pitfalls:

  • IDs must be unique. Duplicate IDs are like twins — they confuse everyone
  • Keep complex expressions in the controller, not in interpolations. Let your templates be simple and clean.