Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: How to get directive's name in the linking function?

I would like to use directive's name inside the linking function. How could I get it?

app.directive('myDirective', function() {
  return {
    link: function(scope, element, attrs) {
      // How could I get directive's name here (i.e. 'myDirective')?
    }
  };
});
like image 465
Misha Moroshko Avatar asked Mar 23 '14 01:03

Misha Moroshko


People also ask

What is linking function in AngularJS?

link function is basically used to manipulate the DOM( Document Object Model ) element using custom directive. link option in custom directive registers DOM listener and also update the DOM. Watch the live demo or download code from the link given below.

What is the naming convention of built in directives in angular 2?

Naming Convention: *[name of directive] — Upper camel case is used for the directive class, while lower camel case is used for the directive's name. What sets them apart from other directives in Angular 2: Reshape DOM structure by adding or removing existing DOM elements and do not have templates.

What does $compile do in AngularJS?

Overview. Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together. The compilation is a process of walking the DOM tree and matching DOM elements to directives. Note: This document is an in-depth reference of all directive options.


2 Answers

It is possible inside compile function of directive.

directives.directive('myNamedDir', ['$compile', function ($compile) {
    return {
        compile: function(cElem, cAttrs, transclude) {
            var name = this.name;
            return function linkFunction(){
                //use name
            }
        }
   }]);
like image 103
oleg wx Avatar answered Sep 22 '22 05:09

oleg wx


Simply define it outside the injection:

var name = 'myDirective';
app.directive(name, function() {
  return {
    link: function(scope, element, attrs) {
      console.log(name); // --> myDirective
    }
  };
});
like image 25
Eliran Malka Avatar answered Sep 19 '22 05:09

Eliran Malka