简体   繁体   English

在AngularJS中获取指令名称

[英]Getting directive name in AngularJS

I've got an Angular directive. 我有一个Angular指令。 Inside the link function, I do this: link函数中,我这样做:

link: function(scope, element, attrs) {
    ...
    element.data('startY', value);
    ...
}

What I'd like to do is perfix 'startY' with the name of the directive, without hard-coding the name. 我想做的是使用指令名称加上前缀'startY' ,而无需对名称进行硬编码。 I'd like to dynamically get the name. 我想动态获取名称。

Is there any way to do this? 有什么办法吗? Does Angular provide a way to reflect it? Angular是否提供一种反映方式? Something like: 就像是:

link: function(scope, element, attrs) {
    ...
    element.data(this.$name + '-startY', value);
    ...
}

If not, what are the recommended best practices for choosing data() keys to avoid collisions? 如果不是,那么为避免冲突而选择data()键的推荐最佳实践是什么?

As indicated in the AngularJS source code , a directive's name is assigned in the context of the object literal where your directive options reside. AngularJS源代码所示 ,在您的指令选项所在的对象文字的上下文中分配指令的名称。 The link function however cannot access the object literal's context, this , because it will be transferred to a compile function where it will be returned and invoked after the compilation process has taken place. 但是,链接函数无法访问对象文字的上下文this ,因为它将被传递到编译函数,在编译过程完成后,该函数将被返回并调用该函数。

To get the name within your link function you can follow any of these suggestions: 要在链接函数中获取名称,可以遵循以下任何建议:

[ 1 ] Create a variable that may hold reference to the object literal(directive options). [1]创建一个变量,该变量可以包含对对象文字的引用(指令选项)。

.directive('myDirective', function() {
  var dir = {
    link: function(scope, elem, attr) {
      console.log(dir.name);
    }
  };
  return dir;
});

[ 2 ] You can also get the directive's name by using the compile function since it is invoked in the context of the directive option. [2]由于指令是在指令选项的上下文中调用的,因此您还可以使用编译函数来获取指令的名称。

.directive('myDirective', function() {
  return {
    compile: function(tElem, tAttr) {
      var dirName = this.name;
      return function(scope, elem, attr) { /* link function */ }
    }
  };
});

As far as I can tell you've answered your own question. 据我所知,您已经回答了自己的问题。 You may prefix the name by string concatenation as you've done but it will probably be easier to add it as a separate data store. 您可以在完成时使用字符串串联作为名称的前缀,但是将其添加为单独的数据存储可能会更容易。

element.data('directiveName', this.$name).data('startY', value);

I'm not sure what you mean by avoid collision as this will only apply to the element that was passed into the link function. 我不确定避免冲突的含义,因为这仅适用于传递给链接函数的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM