1

Im trying to separate my Angular controllers into different files. Right now each one appears like this.

AddPropertyController.js

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

SearchController

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

Now for each one of these I had to include them in the Angular myApp. via:

angular.module('myApp', [
        'myApp.controllers.search',
        'myApp.controllers.addproperty'
    ])

my question is, is there a way to just include them all at once instead of adding them individually? My first attempt was to name each module the same, angular.module('myApp.controllers',...) then just include myApp.controllers in the App. But that didn't seem to work... I guess Im asking is what is the best way to have separated controller files but in all in one module. Thanks for the help!

2 Answers 2

2

Check out the angularjs docs for info on controllers and adding them to app level modules...

For example for your code:

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

myApp.controller('SearchController', ['$scope', function($scope) {
  $scope.search = 'Hola!';
}]);

myApp.controller('AddPropertiesController', ['$scope', function($scope) {
  $scope.props = [];
}]);

You're basically attaching each controller to the myApp instance, so the app is aware of the controllers.

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

5 Comments

I dont think that helps me separate the controllers into different files though... I mean thats how I had it originally but Im using 20+controllers in builds up... When I separate them into different files I dont have access to the myApp variable and if I try to recreate it again i get errors.
@BrentAureli not true, myApp is in window global namespace. I do this all the time and have myApp in numerous files....directives, controllers, services etc. Far simpler than creating modules and then having to chase injection points if you add/remove
you can call angular.module('myApp') - without the second argument, and it will just retrieve the module (it won't try to re-create it)
It's true if you separate the above into JS files, assuming myApp is declared first, it will work ok...
YES! After some more tinkering around, the error is definitely on my part. Thank everyone very much! This worked perfectly!
1

I would organize them like this:

MyController1.js

  var MyController1 = ['$scope', function($scope) {

  }];

MyController2.js

  var MyController2 = ['$scope', function($scope) {
  }];

MyModule.js

  var app = angular.module('MyModule',[]);
  app.controller({
      MyController1: MyController1,
      MyController2: MyController2,
      etc
  });

This is the similar to how the Angular source code is itself organized:

  1. AngularPublic.js
  2. ng Directives

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.