Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`name` in angular directive Definition?

In this document about directive: http://docs.angularjs.org/guide/directive

Directive Definition Object

The directive definition object provides instructions to the compiler. The attributes are:

name - Name of the current scope. Optional and defaults to the name at registration.

I don't understand why the name is the name of current scope? What's the name at registration? If I specify a name, how to use it?

app.directive('aaa', function() {
   return {
      name: 'bbb',
      link: function() {
          // how and where to use the new name `bbb`
      }
   }
}
like image 673
Freewind Avatar asked Mar 07 '13 14:03

Freewind


1 Answers

After some digging around the source code this is what I found: It's a way to declare a separate attribute to assign a controller to the directive dynamically. See plunker.

The idea is to have a way to put the controller reference in a different attribute than the directive name. If the name property is not specified then the directive name will be used as the attribute.

var app = angular.module('angularjs-starter', []);

app.directive('myDirective', [ function() {
  return {
    name : 'myController',
    controller : '@',
    restrict : 'A',
    link : function(scope, elm, attr) {
      console.log('myDirective.link');
    }
  };
} ]);

app.directive('myDirective2', [ function() {
  return {
    controller : '@',
    restrict : 'A',
    link : function(scope, elm, attr) {
      console.log('myDirective2.link');
    }
  };
} ]);

app.controller('MyDirectiveController', [ '$scope', function($scope) {
  console.log('MyDirectiveController.init');
} ]);

app.controller('MyDirectiveController2', [ '$scope', function($scope) {
  console.log('MyDirectiveController2.init');
} ]);

app.controller('MyDirective2Controller', [ '$scope', function($scope) {
  console.log('MyDirective2Controller.init');
} ]);

Template:

<h1 my-directive my-controller="MyDirectiveController">My Directive Controller</h1>
<h1 my-directive my-controller="MyDirectiveController2">My Directive Controller 2</h1>
<h1 my-directive2="MyDirective2Controller">My Directive 2 Controller</h1>

Output:

MyDirectiveController.init
myDirective.link
MyDirectiveController2.init
myDirective.link
MyDirective2Controller.init
myDirective2.link 
like image 92
Liviu T. Avatar answered Nov 16 '22 02:11

Liviu T.