AngularJS - Why have more than one controller

angularjs, javascript

Solution

From what I've seen of it an Angular application should have separate controllers for separate scopes. For instance, almost all applications have user data. You'll want to have this data attached to a user model, inside a user controller:

function UserCtrl ($scope) {
    $scope.user = {
        name: "bmorrow",
        lastLogin: "4/16/2013"
    };
}

And the template (our view) will be inside a specific portion of the applications structure. The right side of a navigation bar for example, or on a user details page. We establish where this portion is by assigning it a controller using `ng-controller`. This creates the `scope` of said controller and binds the corresponding models to it. The model (our data) is connected to the view (the HTML) via the controller.

Suppose the application has a page for the user's written articles. We can create another controller restricted only to the section of HTML that specifically holds the article content.

function ArticleCtrl ($scope) {
    $scope.article = {
        title: "Hello World",
        body: "Lorem ipsum...."
    };
}

In the trivial example above, combining both of the controllers won't do any harm. But once your application begins to grow, logically organizing your controllers/views according to the data it represents will make your code cleaner and easier to understand. Less unneeded complexity will make everything much easier on you. And using one controller for everything is an unneeded complexity.

You can see this illustrated in Basarat's answer as well. You don't necessarily need to use one controller per route, but doing so helps to logically structure the application.

So, to answer your question, you should usually have one controller per category of data. Users, Articles, Fruits, Vegetables, Transactions, and so on.

Read about Angular Controllers and the Model-View-Controller pattern for more information if you haven't already. I hope this helps.

Problem

What reasons are there to have multiple controllers in an AngularJS application? I've built a few angular apps now and I've never encountered a problem where I thought multiple controllers would make things easier for me. I'm still a bit of a n00b, have never written a unit test and my code isn't as manageable as it could be so I'm sure it's just ignorance. And I've heard that other people have multiple controllers. Put another way: how does one know that they should create a new controller?

Original source