2014-02-16 128 views
6

我是新来的角度。我想写一个指令,它具有我在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指令Directive类和其他属性。

输出,我想:<select class="form-control" data-target="elementId"></select>

我用angular.element(element).attr(attr);,但它不工作;

任何帮助提前感谢。

编辑

我希望所有存在的链接功能ATTRS属性被添加到markup

回答

4

根据您的需求的进一步使用的文档here,你并不需要自己编译。您可以使用模板并进行替换。

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是你需要的人。

你可以看看那个阐述逻辑函数

7

我会遍历指令的ATTR阵列,并将其应用到您的模板:

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