简体   繁体   中英

`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`
      }
   }
}

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 

You can change the name of the directives controller, so if you want the controller from another directive you use the new name. This is used by ngForm directive you must type require:'form' instead of require:ngForm .

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