指令模板元素的唯一ID

NoR*_*Ryb 68 templates uniqueidentifier angularjs angularjs-directive

我有一个可以在页面上多次使用的指令.在这个指令的模板中,我需要为input-Element使用ID,所以我可以像这样"绑定"一个Label:

<input type="checkbox" id="item1" /><label for="item1">open</label>
Run Code Online (Sandbox Code Playgroud)

现在问题是,只要多次包含我的指令,ID"item1"就不再是唯一的,并且标签不能正常工作(点击时应选中/取消选中复选框).

这个问题是如何解决的?有没有办法为模板分配"命名空间"或"前缀"(就像asp.net与ctl00 ...-前缀一样)?或者我必须在每个id-Attribute中包含一个angular-Expression,它包含Scope中的指令ID +静态ID.就像是:

<input type="checkbox" id="{{directiveID}} + 'item1'" /><label for="{{directiveID}} + 'item1'">open</label>
Run Code Online (Sandbox Code Playgroud)

编辑:

我的指示

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

我的HTML

<div class="myDirective">
  <input type="checkbox" id="item1" /><label for="item1">open</label>
</div>
Run Code Online (Sandbox Code Playgroud)

Bur*_*riB 91

HTML

    <div class="myDirective">
        <input type="checkbox" id="myItem_{{$id}}" />
        <label for="myItem_{{$id}}">open myItem_{{$id}}</label>
    </div>
Run Code Online (Sandbox Code Playgroud)

  • 优雅的解决方 $ id是$ rootScope为每个子范围提供的唯一范围ID.显然,这可以用于任何具有不同范围的视图,大多数情况都是如此. (9认同)
  • @ penguin359,你可以用```{{:: $ id}}```做一次绑定.当时我的评论是1.3还没有出来. (7认同)
  • 这还应该结合来自@ llan的答案的{{:: expression}}技巧来避免创建更多的手表吗? (6认同)

Ila*_*mer 52

UPDATE

Angular 1.3引入了原生的懒惰一次性绑定.从角度表达文档:

一次性绑定

以::开头的表达式被视为一次性表达式.一次性表达式将在稳定后停止重新计算,如果表达式结果为非未定义值,则会在第一次摘要后发生(请参阅下面的值稳定算法).

原生解决方案:

.directive('myDirective', function() {

    var uniqueId = 1;
    return {
        restrict: 'E',
        scope: true,
        template: '<input type="checkbox" id="{{::uniqueId}}"/>' +
                  '<label for="{{::uniqueId}}">open</label>',
        link: function(scope, elem, attrs) {
            scope.uniqueId = 'item' + uniqueId++;
        }
    }
})
Run Code Online (Sandbox Code Playgroud)

只绑定一次:

  • 如果只需要绑定一个值就不应该使用绑定({{}}/ng-bind)
  • 绑定很昂贵,因为他们使用$ watch.在您的示例中,在每个$ digest上,angular dirty会检查您的ID以进行更改,但您只需设置一次.
  • 检查此模块:https://github.com/Pasvaz/bindonce

解:

.directive('myDirective', function() {

    var uniqueId = 1;
    return {
        restrict: 'E',
        scope: true,
        template: '<input type="checkbox"/><label>open</label>',
        link: function(scope, elem, attrs) {
            var item = 'item' + uniqueId++;
            elem.find('input').attr('id' , item);
            elem.find('label').attr('for', item);
        }
    }
})
Run Code Online (Sandbox Code Playgroud)

  • 应该提到的是,从1.3开始(当时仍在RC中),你可以使用符号`{{:yourExpression}}`进行一次绑定. (3认同)