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
.
Steps to create a custom attribute directiveAssign the attribute directive name to the selector metadata of @Directive decorator. Use ElementRef class to access DOM to change host element appearance and behavior. Use @Input() decorator to accept user input in our custom directive.
Angular attribute directives are a number of built-in directives that we can add to our HTML elements that give them a dynamic behavior. In summary, an attribute directive changes the appearance or behavior of a DOM element.
Attribute binding in Angular helps you set values for attributes directly. With attribute binding, you can improve accessibility, style your application dynamically, and manage multiple CSS classes or styles simultaneously.
Component directive is used to create HTML template. This is most commonly used directive in Angular project. Attribute directive changes the appearance or behavior of DOM element. Structural directive is used to change the DOM layout by adding and removing DOM elements.
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>
Plunkr
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) {
}
};
});
See plnkr
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With