AngularJS


Controllers 1.4.5–1.5.8

0.9.0
0.9.1
0.9.2
0.9.3
0.9.4
0.9.5
0.9.6
0.9.7
0.9.9
0.9.10
0.9.11
0.9.12
0.9.13
0.9.14
0.9.15
0.9.16
0.9.17
0.9.18
0.9.19
0.10.0
0.10.1
0.10.2
0.10.3
0.10.4
0.10.5
0.10.6
1.0.0rc1
g3-v1.0.0rc1
g3-v1.0.0-rc2
v1.0.0rc2
v1.0.0rc3
v1.0.0rc4
v1.0.0rc5
v1.0.0rc6
v1.0.0rc7
v1.0.0rc8
v1.0.0rc9
v1.0.0rc10
v1.0.0rc11
v1.0.0rc12
1.0.0
1.0.1
1.0.2
1.1.0
1.0.3
1.1.1
1.0.4
1.1.2
1.0.5
1.1.3
1.0.6
1.1.4
1.0.7
1.1.5
1.2.0rc1
1.0.8
1.2.0-rc.2
1.2.0-rc.3
1.2.0
1.2.1
1.2.2
1.2.3
1.2.4
1.2.5
1.2.6
1.2.7
1.2.8
1.2.9
1.2.10
1.2.11
1.2.12
1.2.13
1.2.14
1.3.0-beta.1
1.3.0-beta.2
1.3.0-beta.3
1.2.15
1.3.0-beta.4
1.2.16
1.3.0-beta.5
1.3.0-beta.6
1.3.0-beta.7
1.3.0-beta.8
1.3.0-beta.9
1.3.0-beta.10
1.2.17
1.3.0-beta.11
1.2.18
1.3.0-beta.12
1.3.0-beta.13
1.2.19
1.3.0-beta.14
1.2.20
1.3.0-beta.15
1.3.0-beta.16
1.2.21
1.3.0-beta.17
1.2.22
1.3.0-beta.18
1.2.23
1.3.0-beta.19
1.3.0-rc.0
1.2.24
1.3.0-rc.1
1.2.25
1.3.0-rc.2
1.3.0-rc.3
1.3.0-rc.4
1.2.26
1.3.0-rc.5
1.3.0
1.3.1
1.3.2
1.3.3
1.2.27
1.3.4
1.3.5
1.3.6
1.3.7
1.2.28
1.3.8
1.4.0-beta.0
1.3.9
1.3.10
1.4.0-beta.1
1.3.11
1.4.0-beta.2
1.3.12
1.4.0-beta.3
1.3.13
1.4.0-beta.4
1.3.14
1.4.0-beta.5
1.3.15
1.4.0-beta.6
1.4.0-rc.0
1.4.0-rc.1
1.4.0-rc.2
1.4.0
1.3.16
1.4.1
1.3.17
1.4.2
1.4.3
1.4.4
1.3.18
1.4.5
1.3.19
1.4.6
1.5.0-beta.0
1.2.29
1.3.20
1.4.7
1.5.0-beta.1
1.5.0-beta.2
1.4.8
1.5.0-rc.0
1.5.0-rc.1
1.4.9
1.5.0-rc.2
1.5.0
1.4.10
1.5.1
1.5.2
1.5.3
1.5.4
1.5.5
1.4.11
1.5.6
1.4.12
1.5.7
1.2.30
1.5.8

This draft deletes the entire topic.

Introduction

Introduction

expand all collapse all

Examples

  • 24

    A controller is a basic structure used in Angular to preserve scope and handle certain actions within a page. Each controller is coupled with an HTML view.


    Below is a basic boilerplate for an Angular app:

    <!DOCTYPE html>
    
    <html lang="en" ng-app='MyFirstApp'>
        <head>
            <title>My First App</title>
    
            <!-- angular source -->
            <script src="https://code.angularjs.org/1.5.3/angular.min.js"></script>
            
            <!-- Your custom controller code -->
            <script src="js/controllers.js"></script>
        </head>
        <body>
            <div ng-controller="MyController as mc">
                <h1>{{ mc.title }}</h1>
                <p>{{ mc.description }}</p>
                <button ng-click="mc.clicked()">
                    Click Me!
                </button>
            </div>
        </body>
    </html>
    

    There are a few things to note here:

    <html ng-app='MyFirstApp'>
    

    Setting the app name with ng-app lets you access the application in an external Javascript file, which will be covered below.

    <script src="js/controllers.js"></script>
    

    We'll need a Javascript file where you define your controllers and their actions/data.

    <div ng-controller="MyController as mc">
    

    The ng-controller attribute sets the controller for that DOM element and all elements that are children (recursively) below it.

    You can have multiple of the same controller (in this case, MyController) by saying ... as mc, we're giving this instance of the controller an alias.

    <h1>{{ mc.title }}</h1>
    

    The {{ ... }} notation is an Angular expression. In this case, this will set the inner text of that <h1> element to whatever the value of mc.title is.

    Note: Angular employs dual-way data binding, meaning that regardless of how you update the mc.title value, it will be reflected in both the controller and the page.

    Also note that Angular expressions do not have to reference a controller. An Angular expression can be as simple as {{ 1 + 2 }} or {{ "Hello " + "World" }}.

    <button ng-click="mc.clicked()">
    

    ng-click is an Angular directive, in this case binding the click event for the button to trigger the clicked() function of the MyController instance.


    With those things in mind, let's write an implementation of the MyController controller. With the example above, you would write this code in js/controller.js.

    First, you'll need to instantiate the Angular app in your Javascript.

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

    Note that the name we pass here is the same as the name you set in your HTML with the ng-app directive.

    Now that we have the app object, we can use that to create controllers.

    app.controller('MyController', function(){
        var ctrl = this;
    
        ctrl.title = "My First Angular App";
        ctrl.description = "This is my first Angular app!";
    
        ctrl.clicked = function(){
            alert("MyController.clicked()");
        };
    });
    

    Note: For anything that we want to be a part of the controller instance, we use the this keyword.

    This is all that is required to build a simple controller.

  • 9

    There are a couple different ways to protect your controller creation from minification.

    The first is called inline array annotation. It looks like the following:

    var app = angular.module('app');
    app.controller('sampleController', ['$scope', '$http', function(a, b){
        //logic here
    }]);
    

    The second parameter of the controller method can accept an array of dependencies. As you can see I've defined $scope and $http which should correspond to the parameters of the controller function in which a will be the $scope, and b would be $http. Take note that the last item in the array should be your controller function.

    The second option is using the $inject property. It looks like the following:

    var app = angular.module('app');
    app.controller('sampleController', sampleController);
    sampleController.$inject = ['$scope', '$http'];
    function sampleController(a, b) {
        //logic here
    }
    

    This does the same thing as inline array annotation but provides a different styling for those that prefer one option over the other.

    The order of injected dependencies is important

    When injecting dependencies using the array form, be sure that the list of the dependencies match its corresponding list of arguments passed to the controller function.

    Note that in the following example, $scope and $http are reversed. This will cause a problem in the code.

    // Intentional Bug: injected dependencies are reversed which will cause a problem
    app.controller('sampleController', ['$scope', '$http',function($http, $scope) {
        $http.get('sample.json');
    }]);
    
  • 4

    In Angular $scope is the glue between the Controller and the View that helps with all of our data binding needs. Controller As is another way of binding controller and view and is mostly recommended to use. Basically these are the two controller constructs in Angular (i.e $scope and Controller As).

    Different ways of using Controller As are -

    controllerAs View Syntax

    <div ng-controller="CustomerController as customer">
        {{ customer.name }}
    </div>
    

    controllerAs Controller Syntax

    function CustomerController() {
        this.name = {};
        this.sendMessage = function() { };
    }
    

    controllerAs with vm

    function CustomerController() {
        /*jshint validthis: true */
        var vm = this;
        vm.name = {};
        vm.sendMessage = function() { };
    }
    

    controllerAs is syntactic sugar over $scope. You can still bind to the View and still access $scope methods. Using controllerAs, is one of the best practices suggested by the angular core team. There are many reason for this, few of them are -

    • $scope is exposing the members from the controller to the view via an intermediary object. By setting this.*, we can expose just what we want to expose from the controller to the view. It also follow the standard JavaScript way of using this.

    • using controllerAs syntax, we have more readable code and the parent property can be accessed using the alias name of the parent controller instead of using the $parent syntax.

    • It promotes the use of binding to a "dotted" object in the View (e.g. customer.name instead of name), which is more contextual, easier to read, and avoids any reference issues that may occur without "dotting".

    • Helps avoid using $parent calls in Views with nested controllers.

    • Use a capture variable for this when using the controllerAs syntax. Choose a consistent variable name such as vm, which stands for ViewModel. Because, this keyword is contextual and when used within a function inside a controller may change its context. Capturing the context of this avoids encountering this problem.

    NOTE: using controllerAs syntax add to current scope reference to current controller, so it available as field

    <div ng-controller="Controller as vm>...</div>
    

    vm is available as $scope.vm.

Please consider making a request to improve this example.

Syntax

  • <htmlElement ng-controller="controllerName"> ... </htmlElement>
  • <script> app.controller('controllerName', controllerFunction); </script>

Parameters

Parameters

Remarks

Remarks

Still have a question about Controllers? Ask Question

Topic Outline