0

I'm having trouble managing my app. I would like to separate my controllers on several files. I read Brian's Ford blog ( http://briantford.com/blog/huuuuuge-angular-apps.html ) but I cannot quite understand how should I do it.

On my controller.js file I had something like this :

function loginCtrl($scope){
     ....
}

function landingCtrl($scope){
    ...
}

And the only way I found to separate controller per file is to do this:

app.js:

var musicApp = angular.module('musicApp', []);

controller1.js:

musicApp.controller('loginController', ['$scope', loginCtrl],function loginCtrl($scope){
    ....
});

controller2.js:

musicApp.controller('landingCtrl', ['$scope', landingCtrl],function landingCtrl($scope){
    ....
});

Is there a better way to do this?

Community
  • 1
  • 1

3 Answers3

1

I'm using a similar way as below:

Main.js

angular.module('app', []);

FooCtrl.js

angular.module("app").controller("FooCtrl", [
  "$scope", function($scope) {
  }
]);

Another way adopted by google is:

# init empty Object
var docsApp = {
  controller: {},
  directive: {},
  serviceFactory: {}
};

# FooCtrl.js
docsApp.controller.FooCtrl = ['$scope', function($scope){}]

# BarCtrl.js
docsApp.controller.BarCtrl = ['$scope', function($scope){}]

... add services
... directives

# bootstrap angular
angular.module('docsApp', ['...']).
  config(...).
  factory(docsApp.serviceFactory).
  directive(docsApp.directive).
  controller(docsApp.controller);

Take a look at this js from google angularjs tutorial: http://docs.angularjs.org/js/docs.js

Tony Chen
  • 1,804
  • 12
  • 13
-1

You can achieve this in multiple ways.

one file for all your controllers using "."

musicApp.controller('loginController', ['$scope', loginCtrl,function loginCtrl($scope){
    ....
}]).controller('landingCtrl', ['$scope', landingCtrl,function landingCtrl($scope){
    ....
}]);

just remember to include the function inside the injected paramenters array.

or one controller for each file.

just need to include every js file with whatever method you are using (script tag, requirejs, etc.)

-1

I have something similar:

main_router.js:

var myApp = angular.module('theApp', ['controllers'])...

var controllers = angular.module('controllers', []);

some_controller.js:

controllers.controller('SomeCtrl', ['$scope', function ($scope) { ... } ]);

Foo L
  • 10,977
  • 8
  • 40
  • 52