我有一个指令可以在页面上使用多次。在这个指令的模板中,我需要为一个输入元素使用ID,以便我可以将标签与它“绑定”,例如:
<input type="checkbox" id="item1" /><label for="item1">open</label>
现在的问题是,当我的指令被多次包含时,ID“item1”不再是唯一的,标签就无法正常工作了(它应该在单击时选中/取消选中复选框)。
如何解决这个问题?是否有一种方法为模板分配“命名空间”或“前缀”(就像asp.net使用ctl00...-前缀那样)?或者我必须在每个ID属性中包含一个Angular表达式,其中包含来自Scope的指令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>
{{::$id}}
进行一次性绑定。在我发表评论的时候,1.3版本还没有发布。 - BuriB