How to have more than one controllers in AngularJS correctly?

angularjs, javascript

Solution

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.

Problem

I am getting started with AngularJS, and as I understand, I can have different controllers for different sections of my web page. I am having the problem getting it work. I have two sections of my page and corresponding to each one `ng-controller` - JSFiddle. Only the section that come first works. For example currently, `app1` works fine, but when I move it below `app2`, only app2 works fine. What could be wrong? Much appreciate any explanation regarding why this behavior and any links.

Original source