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

心已入冬 提交于 2019-11-26 03:48:26

问题


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 ?


回答1:


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>



回答2:


This thing worked for me pretty well:

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




回答3:


In case you came to this question but related to newer Angular version >= 2.0.

<div [id]="element.id"></div>



回答4:


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.




回答5:


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.




回答6:


Just <input id="field_name_{{$index}}" />




回答7:


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>


来源:https://stackoverflow.com/questions/23655009/how-to-set-the-id-attribute-of-a-html-element-dynamically-with-angularjs-1-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!