AngularJS 中元素的指令模板唯一 ID [英] Directive template unique IDs for elements in AngularJS

查看:27
本文介绍了AngularJS 中元素的指令模板唯一 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以在一个页面上多次使用的指令.在该指令的模板中,我需要为输入元素使用 ID,以便我可以像这样绑定"一个标签:

现在的问题是,一旦我的指令被多次包含,IDitem1"就不再是唯一的,标签也不能正常工作(它应该在点击时选中/取消选中复选框).

这个问题是怎么解决的?有没有办法为模板分配命名空间"或前缀"(就像 asp.net 对 ctl00...-Prefix 所做的那样)?或者我是否必须在每个 id-Attribute 中包含一个 angular-Expression,它由 Scope 中的指令 ID + 一个静态 ID 组成.类似的东西:

<input type="checkbox" id="{{directiveID}} + 'item1'"/><label for="{{directiveID}} + 'item1'">open</标签>

我的指令

module.directive('myDirective', function () {返回 {限制:'E',范围:真实,templateUrl: 'partials/_myDirective.html',控制器:['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {...}//控制器};}]);

我的 HTML

<input type="checkbox" id="item1"/><label for="item1">打开</label>

解决方案

HTML

 

<input type="checkbox" id="myItem_{{$id}}"/><label for="myItem_{{$id}}">打开 myItem_{{$id}}</label>

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>

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).

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>

Edit:

My Directive

module.directive('myDirective', function () {
    return {
        restrict: 'E',
        scope: true, 
        templateUrl: 'partials/_myDirective.html',
        controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {
            ...
        } //controller
    };
}]);

My 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆