[英]How does angular resolve controllers defined in modules?
Looking at the angular documentation for controller there's something that confuses me. 查看控制器的角度文档会使我感到困惑。 Let's say someone does this: 假设有人这样做:
angular.module('foo').controller('controller1', ['$scope', function($scope) {
});
and: 和:
<div ng-app='app' ng-controller='controller1'>
</div>
How does angular know that 'controller1' resides in module 'foo' ? angular如何知道'controller1'驻留在模块'foo'中 ?
And furthermore if someone does this in addition: 此外,如果有人另外这样做:
angular.module('bar').controller('controller1', ['$scope', function($scope) {
});
Which one will angular chose now? 角现在选择哪一个?
When you declare ng-app
here: 在此处声明ng-app
:
<div ng-app='app' ng-controller='controller1'>
</div>
Angular will look for a module definition with the name app
. Angular将寻找名称为app
的模块定义。 Something like this: 像这样:
angular.module('app', []); // notice the []
Inside the second parameter []
array, Angular wants the dependent modules. 在第二个参数[]
数组中,Angular需要依赖模块。 So, in order to include controller1
from foo
module, you would do this: 因此,为了包括foo
模块中的controller1
,您可以这样做:
angular.module('app', ['foo']);
And from the bar
module: 从bar
模块:
angular.module('app', ['bar']);
In each of these, there is only a single controller1
named controller. 在每一个这些,只有一个单一的controller1
名为控制器。
So, what happens when you register both the foo
and bar
modules? 那么,当您同时注册foo
和bar
模块时会发生什么呢? I would think that the last one wins. 我认为最后一个获胜。 So, if you define app
to be: 因此,如果您将app
定义为:
angular.module('app', ['foo', 'bar']);
Then, the bar
module's controller1
will overwrite the name controller1
inside the injector. 然后, bar
模块的controller1
将覆盖注入器内部的名称controller1
。
So, there is no built-in mechanism that allows for the same name to be applied across modules. 因此,没有内置的机制允许在模块之间应用相同的名称。 Because of this, you can employ naming schemes to make sure that the controller is unique: 因此,您可以采用命名方案来确保控制器是唯一的:
angular.module('bar').controller('bar.controller1', ['$scope', function($scope) {
});
How does angular know that 'controller1' resides in module 'foo'? angular如何知道'controller1'驻留在模块'foo'中?
At the time that Angular is resolving controller1
, it doesn't know what module it is in. Once the module is a dependent (on the module defined in ng-app
), all of the controllers (in all modules) are only resolved off of their names. 在Angular解析controller1
,它不知道它在哪个模块中。一旦该模块是一个依赖项(依赖于ng-app
定义的模块),则仅解析所有控制器(在所有模块中)他们的名字。
Angular doesn't really know where the controller comes from. Angular并不真正知道控制器的来源。 Your application includes either foo
or bar
and then controller1
is registered. 您的应用程序包括foo
或bar
,然后注册controller1
。
If you include both foo
and bar
controller1
is from whatever module you included last. 如果同时包含foo
和bar
controller1
则来自上一个包含的模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.