Multiple controllers with AngularJS in single page app

user2539369 picture user2539369 · Jun 19, 2014 · Viewed 238.2k times · Source

I want to know is how to use multiple controllers for a single page application. I have tried to figure it out and I've found questions very similar to mine, but there is just a ton of different answers solving a specific problem where you end up not using multiple controllers for a single page app.

Is that because it would not be wise to use multiple controllers for a single page? Or is it just not possible?

Let's say I already have a kick-ass image carousel controller working the main page, but then I learn how to (let's say) use modals and I need a new controller for that as well (or any other thing I need a controller). What will I do then?

I have seen some answers to other questions where they ask about almost the same things as me and people answer "*OMG. Why would you even do that, just do this...".

What is the best way, or how do you do it?

Edit

Many of you are answering to just declare two controllers and then use ng-controller to call it. I use this bit of code below and then call MainCtrl with ng-controller.

app.config(function($routeProvider, $locationProvider) {                        
  $routeProvider                                                                
       .when('/', {                                            
         templateUrl: "templates/main.html",                                               
         controller:'MainCtrl',                                
        })                                                                      
        .otherwise({                      
            template: 'does not exists'   
        });      
});

Why do I even need to set a controller here if I can just use ng-controller without it? This is what confused me. (and you can't add two controllers this way, I think...)

Answer

J. Bruni picture J. Bruni · Jun 19, 2014

What is the problem? To use multiple controllers, just use multiple ngController directives:

<div class="widget" ng-controller="widgetController">
    <p>Stuff here</p>
</div>

<div class="menu" ng-controller="menuController">
    <p>Other stuff here</p>
</div>

You will need to have the controllers available in your application module, as usual.

The most basic way to do it could be as simple as declaring the controller functions like this:

function widgetController($scope) {
   // stuff here
}

function menuController($scope) {
   // stuff here
}