How to add attributes of element to angular directive
Solution 1
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) {
}
};
});
Solution 2
I would iterate over directive's attr array and apply it to your template:
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]);
}
}
}
};
})
Directive Tag:
<province foo="bar" foo1="bar1"></province>
Compiled into:
<select foo="bar" foo1="bar1"></select>
Solution 3
You can make use of the attrs
parameter of the linking function - this will get you the values of the attributes:
attrs.class
and attrs.dataTarget
are the ones you need.
You can take a look at the documentation here that elaborates further uses of the linking function
Beginner
Updated on February 17, 2020Comments
-
Beginner over 4 years
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:
This is my directive
'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>
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>
I used
angular.element(element).attr(attr);
, but it does not worked;Any help is appreciated in advance.
Edit
I want all the attributes that exist in attrs of link function to be added to
markup
. -
Dustin over 10 yearsI don't know this answer isn't accepted, yet, but THANK YOU! This is avery simple solution, and I didn't see it in any of the tutorials that I've been over, yet.