1

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?

1
  • 1
    I dont think the directive's name is exposed somehow, but how about keeping it in a variable ? (var dirName = '...'; app.directive(dirName, ...);) Commented Jun 4, 2014 at 14:51

2 Answers 2

1

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 */ }
    }
  };
});
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.