How to add attributes of element to angular directive

断了今生、忘了曾经 提交于 2019-12-21 12:49:53

问题


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.


回答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) {
        }
    };
});

See plnkr




回答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>

Plunkr




回答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



来源:https://stackoverflow.com/questions/21813280/how-to-add-attributes-of-element-to-angular-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!