在本文中关于指令:
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.
我不明白为什么名字是当前范围的名称?注册的名称是什么?如果我指定一个名字,怎么用呢?
- app.directive('aaa',function() {
- return {
- name: 'bbb',link: function() {
- // how and where to use the new name `bbb`
- }
- }
- }
在一些挖掘源代码之后,这是我发现的:
这是一种声明一个单独的属性以动态地将控制器分配给该指令的方式.见 plunker.
这是一种声明一个单独的属性以动态地将控制器分配给该指令的方式.见 plunker.
这个想法是将控制器引用放在与指令名称不同的属性中.如果未指定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 : '@',attr) {
- console.log('myDirective2.link');
- }
- };
- } ]);
- app.controller('MyDirectiveController',[ '$scope',function($scope) {
- console.log('MyDirectiveController.init');
- } ]);
- app.controller('MyDirectiveController2',function($scope) {
- console.log('MyDirectiveController2.init');
- } ]);
- app.controller('MyDirective2Controller',function($scope) {
- console.log('MyDirective2Controller.init');
- } ]);
模板:
- <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>
输出:
- MyDirectiveController.init
- myDirective.link
- MyDirectiveController2.init
- myDirective.link
- MyDirective2Controller.init
- myDirective2.link