简体   繁体   中英

Getting directive name in AngularJS

I've got an Angular directive. Inside the link function, I do this:

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. I'd like to dynamically get the name.

Is there any way to do this? Does Angular provide a way to reflect it? 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?

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. 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.

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).

.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.

.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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