How to have more than one controllers in AngularJS correctly?

You can have multiple controllers, but you cannot have multiple ng-app directives on the same page. This means you should only have a single ng-app directive in your html that points to a single module that will be used in your application.

You then define this module and define all your controllers in this module:

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

app.controller('TextController', function ($scope) {
    //Controller Code Here    
});

app.controller('ItemController', function ($scope) {
    //Controller Code Here
});

If for some reason you want to have controllers in separate modules, you can still do that, and include those modules as dependencies of your main module:

var items = angular.module('items', []);
var text = angular.module('text', []);
var app = angular.module('app', ['items', 'text']);


text.controller('TextController', function ($scope) {
    //Controller Code Here
});

items.controller('ItemController', function ($scope) {
    //Controller Code Here
});

Generally you don’t need to have a module for each controller. Modules are used to group related pieces of functionality together to make it easy to take that and re-use it in another application.

Here are links to some examples:

Single Module : http://jsfiddle.net/36s7q/4/

Multiple Modules: http://jsfiddle.net/36s7q/5/

Notice how in both example there is only a single ng-app on the page.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)