如何将元素属性添加到Angular指令中

6

我是新手学习Angular。我想编写一个指令,它可以在HTML中使用时添加所有属性。例如:

这是我的指令

'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>

我希望我的<select>标签包含我在HTML中指令中添加的class和其他属性。
期望输出结果:<select class="form-control" data-target="elementId"></select> 我使用了angular.element(element).attr(attr);,但它没有起作用;
非常感谢您能提供任何帮助。 编辑 我希望将链接函数中attrs中存在的所有属性添加到markup中。
3个回答

8
我会遍历指令的属性数组,并将其应用于您的模板:
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]);
        }
      }
     }
};

})

指令标签:

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

编译成:

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

Plunkr


5

根据您的需求,您不需要自行编译。您可以使用模板并进行替换。

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

See plnkr


1
我不知道为什么这个答案还没有被接受,但是非常感谢!这是一个非常简单的解决方案,而且我在我看过的所有教程中都没有看到过。 - Dustin

1
你可以利用链接函数的attrs参数 - 这将使您获得属性的值: attrs.classattrs.dataTarget是您需要的。
您可以查看这里的文档,详细介绍了链接函数的其他用途。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接