分配指令属性模板元素 [英] Assign directive attributes to an element in template
问题描述
我这是应该做一个指令,我选择一个小票友:
I have a directive which is supposed to make my select a little fancier:
angular.module('myDeadLine')
.directive('dcSelect', function () {
return {
restrict: 'E',
scope: {
label: '@',
ngModel: '=',
ngOptions: '=',...
},
transclude: true,
templateUrl: '/web/_utils/dcselect/dcselect.html'
};
});
与模板:
<div class="form-group">
<select class="form-control"
ng-focus="dcSelectFocused=true"
ng-blur="dcSelectFocused=false">
<option value="">{{label}}</option>
</select>
<i class="fa fa-arrow-down" ng-class="{ 'open': dcSelectFocused }"></i>
</div>
什么是分配上的所有选择与属性选择标记,所以我可以使用它像最简单的方法:
What is the easiest way to assign all select related attributes on to the select tag so I can use it like this:
<dc-select label="Select something" ng-model="model" ng-options="" and so on></dc-select>
有没有用,我可以将所有的属性,除了标签来选择,并让他们发挥作用?自动的方式
Is there an automated way by which I can transfer all attributes to select except "label", and have them function?
推荐答案
这是有效的情况下,但是从角的阻力并不能使一个简单的任务来完成。通常替换:真正的
用于所有属性的子模板元素转移。但选择
不是嫡系,它不是一个选项。
It is the valid scenario, but the resistance from Angular doesn't make it a trivial task to do. Usually replace: true
is used to transfer all the attributes to the child template element. But select
isn't a direct descendant, it is not an option.
另一种可能是使用端子:真正的
在高优先级
,因为 NG-模型
, NG-选项
和任何其他属性的指令不应该在 DC选
元素。但端子:真正的
也将无法正常工作(在这种情况下,他们必须手动插值)停止绑定
The other possibility is to use terminal: true
in conjunction with high priority
, because ng-model
, ng-options
and any other attribute directives shouldn't be compiled on dc-select
element. But terminal: true
would also stop the bindings from working (in this case they have to be interpolated manually).
我想最简单的方法就是
.directive('dcSelect', function ($compile) {
return {
restrict: 'E',
scope: {
label: '@',
dcNgModel: '=',
dcNgOptions: '='
},
transclude: true,
templateUrl: '/web/_utils/dcselect/dcselect.html',
link: function (scope, element, attrs) {
var select = element.find('select');
angular.forEach(attrs.$attr, function (name, normalizedName) {
if (!name.match(/^dc-/)) return;
var val = scope.hasOwnProperty(normalizedName) ? normalizedName : element.attr(name);
select.attr(name.replace(/^dc-/, ''), val);
});
$compile(select)(scope);
}
};
});
这篇关于分配指令属性模板元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!