如何将元素的属性添加到 angular 指令 [英] How to add attributes of element to angular directive
问题描述
我是 angular 的新手.我想编写一个指令,其中包含我在 html 中使用时添加的所有属性.例如:
I'm new to angular. I want to write a directive which has all the attributes that I added to it when using in html. For example:
这是我的指令
'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>
我希望我的 包含我添加到 html 指令中的类和其他属性.
I want my <select>
contain the class and other attributes that I added to directive in html.
我想要的输出:
output that I want: <select class="form-control" data-target="elementId"></select>
我使用了 angular.element(element).attr(attr);
,但它不起作用;
I used angular.element(element).attr(attr);
, but it does not worked;
提前感谢任何帮助.
编辑
我希望将链接函数 attrs 中存在的所有属性添加到 markup
.
I want all the attributes that exist in attrs of link function to be added to markup
.
推荐答案
根据您的需要,您不需要自己编译.您可以使用模板并替换.
Depending on your needs, you don't need to compile yourself. You can use template and replace instead.
app.directive('province', function() {
return {
restrict: 'E',
template: '<select></select>',
replace: true,
link: function (scope, element, attrs) {
}
};
});
这篇关于如何将元素的属性添加到 angular 指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!