gpt4 book ai didi

javascript - 将指令属性分配给模板中的元素

转载 作者:行者123 更新时间:2023-11-30 00:22:30 25 4
gpt4 key购买 nike

我有一个指令应该让我的选择更漂亮:

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>

将所有 select 相关属性分配给 select 标签的最简单方法是什么,这样我就可以像这样使用它:

<dc-select label="Select something" ng-model="model" ng-options="" and so on></dc-select>

是否有一种自动化的方式可以将除“标签”之外的所有属性传输到 select,并使它们发挥作用?

最佳答案

这是一个有效的场景,但来自 Angular 的阻力并没有使它成为一项微不足道的任务。通常使用replace: true 将所有属性传递给子模板元素。但是 select 不是直接后代,它不是一个选项。

另一种可能性是将 terminal: true 与高 priority 结合使用,因为 ng-model, ng-options 和任何其他属性指令不应在 dc-select 元素上编译。但是 terminal: true 也会阻止绑定(bind)工作(在这种情况下,它们必须手动插入)。

我想最简单的方法是

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

关于javascript - 将指令属性分配给模板中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32657670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com