0

There is this SO question that seems to imply it is possible to use controllers from different modules by defining tag attributes like:

<div ng-controller="submodule1.controller1">{{ whatever1 }}</div>
<div ng-controller="submodule2.controller2">{{ whatever2 }}</div>

and by bootstrapping angular with a module that contains both submodule1 and submodule2 as dependencies.

I've been trying to do so without success. Can anyone confirm this is not possible or provide a pointer to a working example of this construction?

I am talking explicitly about ng-controller tag attributes and not about having controllers interact programmatically with each other.

I am also explicitly referring to manual angular.bootstrap(document, ['myApp']) of the page, because I am using require.js to load all JS files and therefore I cannot use the ng-app attribute.

I am using angular 1.3.18.

Community
  • 1
  • 1
Marco Faustinelli
  • 3,734
  • 5
  • 30
  • 49

2 Answers2

2

Once the modules are loaded, Angular is unable to make a difference between their components. It is

<div ng-controller="controller1">{{ whatever1 }}</div>
<div ng-controller="controller2">{{ whatever2 }}</div>

Unless they were defined as

angular.module('submodule1').controller('submodule1.controller1', ...)
...

(and they possibly shouldn't be because there's no convention for this and no obvious benefit).

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
1

The concept of modules are only used to put things/features in groups/encapsulation.When modules are compiled and loaded, all of their contained factories/services/controllers,etc are added to angular's injection container. Once they are in the IC, there is no way to find out which module something came from.

You can directly reference the controller without specifying the module itself. @estus has pointed out, you can do:

<div ng-controller="controller1">{{ whatever1 }}</div>
<div ng-controller="controller2">{{ whatever2 }}</div>

If you have multiple modules with the containing the same controller/service name, then it gets a bit more complicated. If I am not mistaken, the module that's the closest to your main module, 'myApp', will be used.

If multiple directives share the same name, rather than overriding one another, they behave more like a decorator pattern where they complement each other.

Henry Zou
  • 1,809
  • 1
  • 14
  • 19