gpt4 book ai didi

angularjs - 如何将元素的属性添加到 Angular 指令

转载 作者:行者123 更新时间:2023-12-02 23:53:15 24 4
gpt4 key购买 nike

我是 Angular 新手。我想编写一个指令,其中包含我在 html 中使用时添加到其中的所有属性。例如:

这是我的指令

'use strict';
app.directive('province', function($compile) {
return {
restrict: 'E',
link: function (scope, element, attrs, controller) {
var markup = "<select></select>";
var elem = angular.element(element);
elem.replaceWith($compile(markup)(scope));
}
};

})

HTML:

<province class="form-control" data-target"elemntId"></province>

我想要我的<select>包含我添加到 html 指令中的类和其他属性。

我想要的输出:<select class="form-control" data-target="elementId"></select>

我用过angular.element(element).attr(attr); ,但它不起作用;

提前感谢任何帮助。

编辑

我希望将链接函数的 attrs 中存在的所有属性添加到 markup .

最佳答案

我将迭代指令的 attr 数组并将其应用到您的模板:

app.directive('province', function($compile) {
return {
restrict: 'E',
replace:true,
template: "<select></select>",
link: function (scope, element, attrs) {
var attr;
for (attr in attrs.$attr) {
if(attrs.hasOwnProperty(attr)){
element.attr(attr, attrs[attr]);
}
}
}
};

})

指令标签:

<province foo="bar" foo1="bar1"></province>

编译为:

<select foo="bar" foo1="bar1"></select>

Plunkr

关于angularjs - 如何将元素的属性添加到 Angular 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21813280/

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