AngularJS – Why use “Controller as vm”?

One advantage of using the controller as syntax is that it allows you to define your controllers as a simple javascript constructor function with properties and functions exposed directly from the instantiated object rather than the $scope.

For example:

function MyController() {

    var ctl = this;

    ctl.message="You have not clicked anything yet.";

    ctl.onClick = function() {
        ctl.message="You clicked something.";
    };

    return ctl;
}

...

myModule.controller('MyController', MyController);

...

<div ng-controller="MyController as vm">
    <span>{{vm.message}}</span>
    <button ng-click="vm.onClick()">Click Me</button>
</div>

Notice that we are able to use a controller that is plain old javascript without even being tied to angular. For scenarios where you need additional dependencies such as $scope or other services, you can still easily pass them in to your constructor, but this pattern encourages less clutter directly on your $scope and also solves the problem of variable hiding when variables are set directly on the scope.

Ultimately it really comes down to a matter of preference, but for me I really like not having to define everything directly on the scope and to treat my controllers as any old javascript object as much as possible.

Here’s an excellent article on the usage of controller as:
http://www.johnpapa.net/angularjss-controller-as-and-the-vm-variable/

Leave a Comment