How to add element attributes to angular directive

I am new to angular. I want to write a directive that has all the attributes that I added to it when used in html. For instance:

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 the directive in html.

which I want: <select class="form-control" data-target="elementId"></select>

I used angular.element(element).attr(attr); but it did not work;

Any help is appreciated in advance.

Edit

I want all the attributes that exist in the attrs link function to be added to markup .

+6
source share
3 answers

Depending on your needs, you do not need to compile yourself. Instead, you can use a template and replace.

 app.directive('province', function() { return { restrict: 'E', template: '<select></select>', replace: true, link: function (scope, element, attrs) { } }; }); 

See plnkr

+4
source

I will iterate over the attr array as a directive 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]); } } } }; 

})

Directory tag:

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

Compiled to:

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

Plunkr

+7
source

You can use the attrs parameter of the binding function - this will give you attribute values:

attrs.class and attrs.dataTarget are the ones you need.

You can look at the documentation here , which details binding functions.

+1
source

All Articles