0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.