AngularJS中元素的指令模板唯一ID [英] Directive template unique IDs for elements in AngularJS
问题描述
我有一个可以在页面上多次使用的指令.在此指令的模板中,我需要对输入元素使用ID,以便可以像这样将标签"绑定"到它:
I have a directive that can be used multiple times on a page. In the template of this directive, I need to use IDs for an input-Element so I can "bind" a Label to it like so:
<input type="checkbox" id="item1" /><label for="item1">open</label>
现在的问题是,多次包含我的指令后,ID"item1"不再是唯一的,标签也无法正常工作(单击时应选中/取消选中该复选框).
Now the problem is, as soon as my directive is included multiple times, the ID "item1" is not unique anymore and the label doesn't work correctly (it should check/uncheck the checkbox when clicked).
该问题如何解决?有没有一种方法可以为模板分配名称空间"或前缀"(例如asp.net使用ctl00 ...- Prefix)?还是我必须在每个id属性中包括一个angular-Expression,它由作用域中的指令ID +一个静态ID组成.像这样:
How is this problem fixed? Is there a way to assign a "namespace" or "prefix" for the template (like asp.net does with the ctl00...-Prefix)? Or do I have to include an angular-Expression in each id-Attribute which consists of the directive-ID from the Scope + a static ID. Something like:
<input type="checkbox" id="{{directiveID}} + 'item1'" /><label for="{{directiveID}} + 'item1'">open</label>
我的指令
module.directive('myDirective', function () {
return {
restrict: 'E',
scope: true,
templateUrl: 'partials/_myDirective.html',
controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {
...
} //controller
};
}]);
我的HTML
<div class="myDirective">
<input type="checkbox" id="item1" /><label for="item1">open</label>
</div>
推荐答案
HTML
<div class="myDirective">
<input type="checkbox" id="myItem_{{$id}}" />
<label for="myItem_{{$id}}">open myItem_{{$id}}</label>
</div>
这篇关于AngularJS中元素的指令模板唯一ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!