6

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.

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

Comments

5

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

1 Comment

I 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.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.