简体   繁体   English

角度指令定义中的`name`?

[英]`name` in angular directive Definition?

In this document about directive: http://docs.angularjs.org/guide/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 . name - 当前范围的名称 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 . 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. 如果未指定name属性,则将使用指令名称作为属性。

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 . 这是由ngForm指令使用,您必须键入require:'form'而不是require:ngForm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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