Episode 9 of 25

Controllers

Learn how to create controllers to manage your application logic and data.

Controllers are JavaScript functions that manage the data and logic for a section of your view. They are the "C" in MVC.

Creating a Controller

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

app.controller('MainCtrl', function($scope) {
    $scope.title = "My App";
    $scope.message = "Welcome to AngularJS!";
});
<div ng-controller="MainCtrl">
    <h1>{{ title }}</h1>
    <p>{{ message }}</p>
</div>

The $scope Object

$scope is the glue between the controller and the view. Any property added to $scope is available in the HTML template:

app.controller('UserCtrl', function($scope) {
    // Data
    $scope.user = {
        name: "Alice",
        age: 25,
        hobbies: ["Reading", "Coding", "Gaming"]
    };

    // Methods
    $scope.greet = function() {
        return "Hello, " + $scope.user.name + "!";
    };

    $scope.addHobby = function(hobby) {
        $scope.user.hobbies.push(hobby);
    };
});
<div ng-controller="UserCtrl">
    <h2>{{ greet() }}</h2>
    <p>Age: {{ user.age }}</p>
    <ul>
        <li ng-repeat="hobby in user.hobbies">{{ hobby }}</li>
    </ul>
</div>

Multiple Controllers

<div ng-controller="HeaderCtrl">
    <h1>{{ title }}</h1>
</div>

<div ng-controller="ContentCtrl">
    <p>{{ content }}</p>
</div>

Each controller has its own $scope — they don't share data by default.