Generate a dynamic HTML id with Angular JS

10 views
Skip to first unread message

francesco real

unread,
Jun 25, 2020, 8:54:19 AM6/25/20
to Angular and AngularJS discussion
hello I try to generate an html id in the form a + {{r}} r being the browse of ng-repeat when I want to recover the id my js recovered #a {{r}} instead of # a1 or in my html code id = a1 id = a2 ...

code html :

<div ng-controller="ddController" >
               <div class="containerslot" ng-controller="myCtrl">
                       <div ng-repeat="r in [1,2, 3, 4, 5, 6, 7, 8, 9, 10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27]">
                           <span class="slot grey" id="a{{r}}" ng-repeat="c in [1]" x-lvl-draggable='true' x-lvl-drop-target="true" x-on-drop="dropped(dragEl, dropEl)" ng-dblclick="showTabDialog(r)" data-color="grey"><button style="margin-right: 145px;
                               height: 22px;
                               display: block;" ng-click="openUserProfile(r)">config</button></span>
                       </div>
                   </div>
               </div>

js value 
var src = document.getElementById(data);
var dest = document.getElementById(id);
                   
                   console.log(src)
                   console.log(dest)

src and dest not value because id = #a{{r}}

Sander Elias

unread,
Jun 29, 2020, 12:19:06 AM6/29/20
to Angular and AngularJS discussion
Hi Francesso,

You can not create an DOM id like that. The browser only allows you to set the ID once, and it doesn't change anymore after that.
Your code will set the id to:
 "a{{r}}"
Wich is a valid Id, but not really usable.
The best thing you can do is not rely on `id`'s in the first place. If you need to interact with 3rth party things, use the data attribute instead, and select on that.

Regards
Sander
Reply all
Reply to author
Forward
0 new messages