angularjs:是否可以从自我指令编译函数访问指令名称?

时间:2014-04-02 13:14:40

标签: angularjs angularjs-directive

是否可以从自我指令编译功能访问指令名? 只是为了更好地解释我的意思:

app.directive('myDirective', function() {
  return {
    scope: {},
    compile: function(element, attrs) {
      if (!attr.mandatoryParameter) return err(element, 'mandatory parameter not specified!');
      element.replaceWith('... ok ...');
    }
  };

  function err(el, reason) {
    el.replaceWith(I_WOULD_LIKE_TO_PRINT_MY_DIRECTIVE_HERE__ + ': ' + reason);
  }
});

2 个答案:

答案 0 :(得分:3)

compile: function(element, attrs) {
    console.log(this.name);
}

答案 1 :(得分:-1)

你可以将它存储在一个变量中,在这种情况下我会把它放在一个闭包中,所以它不在全局命名空间中:

(function() {
  directiveName = 'myDirective';

  app.directive(directiveName, function() {
    // ...

    function err(el, reason) {
      el.replaceWith(directiveName + ': ' + reason);
    }
  });
})();