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)
Ila*_*mer 52
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)
解:
.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)
| 归档时间: |
|
| 查看次数: |
59482 次 |
| 最近记录: |