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' ?
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:
<div ng-app='app' ng-controller='controller1'>
</div>
Angular will look for a module definition with the name app
. Something like this:
angular.module('app', []); // notice the []
Inside the second parameter []
array, Angular wants the dependent modules. So, in order to include controller1
from foo
module, you would do this:
angular.module('app', ['foo']);
And from the bar
module:
angular.module('app', ['bar']);
In each of these, there is only a single controller1
named controller.
So, what happens when you register both the foo
and bar
modules? I would think that the last one wins. So, if you define app
to be:
angular.module('app', ['foo', 'bar']);
Then, the bar
module's controller1
will overwrite the name controller1
inside the injector.
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'?
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 doesn't really know where the controller comes from. Your application includes either foo
or bar
and then controller1
is registered.
If you include both foo
and bar
controller1
is from whatever module you included last.
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.