Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
angularjs:是否可以从自指令编译函数访问指令名?_Angularjs_Angularjs Directive - Fatal编程技术网

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

angularjs:是否可以从自指令编译函数访问指令名?,angularjs,angularjs-directive,Angularjs,Angularjs Directive,是否可以从自指令编译函数访问指令名? 为了更好地解释我的意思: app.directive('myDirective', function() { return { scope: {}, compile: function(element, attrs) { if (!attr.mandatoryParameter) return err(element, 'mandatory parameter not specified!'); element.r

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

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);
  }
});

您可以将其存储在变量中,在这种情况下,我会将其放在闭包中,这样它就不在全局命名空间中:

(function() {
  directiveName = 'myDirective';

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

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

你为什么不硬编码呢?我不喜欢重复编码…:-)对,但不那么“优雅”…:-)
compile: function(element, attrs) {
    console.log(this.name);
}