Angularjs 如何向angular指令添加元素属性
我是新手。我想写一个指令,它包含我在html中使用时添加到它的所有属性。例如: 这是我的指令Angularjs 如何向angular指令添加元素属性,angularjs,angularjs-directive,Angularjs,Angularjs Directive,我是新手。我想写一个指令,它包含我在html中使用时添加到它的所有属性。例如: 这是我的指令 'use strict'; app.directive('province', function($compile) { return { restrict: 'E', link: function (scope, element, attrs, controller) { var markup = "<select></
'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));
}
};
})
“严格使用”;
应用指令('province',函数($compile){
返回{
限制:'E',
链接:功能(范围、元素、属性、控制器){
var标记=”;
var elem=角度元素(元素);
元素替换为($compile(markup)(scope));
}
};
})
HTML:
我希望我的
包含我在html中添加到指令中的类和其他属性
我想要的输出:
我使用了angular.element(element).attr(attr)代码>,但它不起作用
任何帮助都将提前得到感谢
编辑
我希望链接函数的attrs中存在的所有属性都添加到标记中您可以使用链接函数的attrs
参数-这将获得属性值:
attrs.class
和attrs.dataTarget
是您需要的
您可以查看详细说明链接函数进一步使用的文档根据您的需要,您无需自行编译。您可以使用模板替换
app.directive('province', function() {
return {
restrict: 'E',
template: '<select></select>',
replace: true,
link: function (scope, element, attrs) {
}
};
});
app.directive('province',function(){
返回{
限制:'E',
模板:“”,
替换:正确,
链接:函数(范围、元素、属性){
}
};
});
我将迭代指令的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]);
}
}
}
};
app.directive('province',function($compile){
返回{
限制:'E',
替换:正确,
模板:“”,
链接:函数(范围、元素、属性){
var-attr;
用于(属性中的属性$attr){
if(属性hasOwnProperty(属性)){
attr(attr,attrs[attr]);
}
}
}
};
})
指令标签:
<province foo="bar" foo1="bar1"></province>
汇编成:
<select foo="bar" foo1="bar1"></select>
我不知道这个答案还没有被接受,但谢谢你!这是一个非常简单的解决方案,我还没有在我看过的任何教程中看到它。
<select foo="bar" foo1="bar1"></select>