AngularJS Modules and External Controllers

MGot90 picture MGot90 · Aug 27, 2014 · Viewed 8k times · Source

I have a page containing multiple containers. Each container will have its own controller but point to one factory, which handles all the logic interacting with a web service API. I would like to have a separate file for each controller BUT I want all of this inside of one module. for the life of me I cannot find how to include controllers from different files into one modules.

//file 1
MyController ....

//file 2
MyOtherController

//file 3
MyFactory

//file 4
The Module

The module would be composed of MyController, MyOtherController and MyFactory defined in three separate files. Can someone help with this or point me to a good resource? Thanks!

Answer

user1952312 picture user1952312 · Aug 27, 2014

You can think of a module as a container for the different parts of your app – controllers, services, filters, directives, etc. To access a container just call its module name for example

//file.4

angular.module("theModule",[]);

now that you have declared main module within angular now you can access mainModule from anywhere using angular

//file 1

angular.module("theModule").controller("MyController",[function(){...}]);

//file 2

angular.module("theModule").controller("MyOtherController",[function(){...}]);

//file 3

angular.module("mainModule").factory("MyFactory",[function(){...}]);

Check out the documentation for more information.

I also suggest reading Google's style guide and conventions manual

Also read about setting up app structure for maintainability