How to create separate AngularJS controller files? How to create separate AngularJS controller files? angularjs angularjs

How to create separate AngularJS controller files?


File one:

angular.module('myApp.controllers', []);

File two:

angular.module('myApp.controllers').controller('Ctrl1', ['$scope', '$http', function($scope, $http){}]);

File three:

angular.module('myApp.controllers').controller('Ctrl2', ['$scope', '$http', function($scope, $http){}]);

Include in that order. I recommend 3 files so the module declaration is on its own.


As for folder structure there are many many many opinions on the subject, but these two are pretty good

https://github.com/angular/angular-seed

http://briantford.com/blog/huuuuuge-angular-apps.html


Using the angular.module API with an array at the end will tell angular to create a new module:

myApp.js

// It is like saying "create a new module"angular.module('myApp.controllers', []); // Notice the empty array at the end here

Using it without the array is actually a getter function. So to seperate your controllers, you can do:

Ctrl1.js

// It is just like saying "get this module and create a controller"angular.module('myApp.controllers').controller('Ctrlr1', ['$scope', '$http', function($scope, $http) {}]);

Ctrl2.js

angular.module('myApp.controllers').controller('Ctrlr2', ['$scope', '$http', function($scope, $http) {}]);

During your javascript imports, just make sure myApp.js is after AngularJS but before any controllers / services / etc...otherwise angular won't be able to initialize your controllers.


Although both answers are technically correct, I want to introduce a different syntax choice for this answer. This imho makes it easier to read what's going on with injection, differentiate between etc.

File One

// Create the module that deals with controllersangular.module('myApp.controllers', []);

File Two

// Here we get the module we created in file oneangular.module('myApp.controllers')// We are adding a function called Ctrl1// to the module we got in the line above.controller('Ctrl1', Ctrl1);// Inject my dependenciesCtrl1.$inject = ['$scope', '$http'];// Now create our controller function with all necessary logicfunction Ctrl1($scope, $http) {  // Logic here}

File Three

// Here we get the module we created in file oneangular.module('myApp.controllers')// We are adding a function called Ctrl2// to the module we got in the line above.controller('Ctrl2', Ctrl2);// Inject my dependenciesCtrl2.$inject = ['$scope', '$http'];// Now create our controller function with all necessary logicfunction Ctrl2($scope, $http) {  // Logic here}