我有一个可以在页面上多次使用的指令。在此指令的模板中,我需要使用输入元素的 ID,以便我可以将标签“绑定(bind)”到它,如下所示:
<input type="checkbox" id="item1" /><label for="item1">open</label>
现在的问题是,一旦我的指令被多次包含,ID“item1”就不再是唯一的,标签也无法正常工作(单击时应该选中/取消选中复选框)。
这个问题是如何解决的?有没有办法为模板分配“命名空间”或“前缀”(就像asp.net使用ctl00...-前缀那样)?或者我是否必须在每个 id 属性中包含一个 Angular 表达式,该表达式由范围中的指令 ID + 静态 ID 组成。像这样的东西:
<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 - AngularJS 中元素的指令模板唯一 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21021951/