AngularJS:如何在链接函数中获取指令的名称?

时间:2014-03-23 01:31:39

标签: angularjs angularjs-directive

我想在链接函数中使用指令的名称。我怎么能得到它?

app.directive('myDirective', function() {
  return {
    link: function(scope, element, attrs) {
      // How could I get directive's name here (i.e. 'myDirective')?
    }
  };
});

3 个答案:

答案 0 :(得分:9)

指令compile函数内部可以使用。

directives.directive('myNamedDir', ['$compile', function ($compile) {
    return {
        compile: function(cElem, cAttrs, transclude) {
            var name = this.name;
            return function linkFunction(){
                //use name
            }
        }
   }]);

答案 1 :(得分:6)

只需在注射之外定义它:

var name = 'myDirective';
app.directive(name, function() {
  return {
    link: function(scope, element, attrs) {
      console.log(name); // --> myDirective
    }
  };
});

答案 2 :(得分:0)

app.directive('myDirective', function() {
    return {
        link: function(scope, element, attrs) {
            console.log(arguments.callee.directiveName); // --> myDirective
        }
    };
});

JavaScript中不推荐使用arguments.callee.caller属性