angularjs - AngularJS 中元素的指令模板唯一 ID

标签 angularjs templates angularjs-directive uniqueidentifier

我有一个可以在页面上多次使用的指令。在此指令的模板中,我需要使用输入元素的 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/

相关文章:

javascript - Angular Jasmine 测试因缩小源而失败

c++ - 防止模板参数上的 ADL

c++ - 为类模板重载运算符<<

javascript - Angular.js 在 Controller 中调用指令函数

css - 在动态选项对象上删除 Angular 上的空白选项

javascript - 使用 angularjs 观察下拉列表的选定值以填充数组取决于选定的值

C++ 模板 : override some, 但不是全部,默认参数?

javascript - 解析有什么用以及如何从弹出屏幕发送数据以在 Angular JS 中查看?

javascript - 如何在 AngularJS 自己的指令中使用 ng-class 和函数?

javascript - AngularJs 多个同名 Controller 在一个文件中隔离作用域