AngularJs – “controller as” Syntax

May 11, 2015
by Rahil Shaikh

I’m quite a bit late with this post about “controller as” syntax in AngularJs, but I’ve always wanted to use this model in all my previous articles.
However I thought it would not be appropriate to use that method unless I explain to my readers how to use it an how is it more advantageous over the standard $scope model.

What is it ?

When using “controller as” syntax you declare your controller in your view with an alias, and then use the alias to refer to the controller.

ng-controller=”fooCtrl as foo”

And inside your controller you would declare functions and variables on the “this” keyword instead of binding them to the $scope.

This gives you a feel of proper instantiation and a class like declaration with the “this” key word.

Why use “controller as” Syntax

Using controller as syntax resembles class like declaration of javascript.
Using it makes your views more readable and clean.
A huge advantage can be seen when nesting controllers, it avoids the usual reference to parent controllers using $parent

Example:

View or Html
<div ng-controller = "bossCtrl as boss">
    <div ng-controller = "anotherCtrl as another">
         <div ng-controller = "oneMoreCtrl as one">
                   {{boss.name}}
                   {{another.name}}
                   {{one.name}}  <!-- the classic way will involve $parent.$parent.name -->
             </div>
        </div>
</div>

Here the name refers to the one declared on the respective controllers.

It promotes the binding to the dotted object, which is more easier to read and avoids reference issues as you can see above.

What about $scope?

“controller as” syntax is really great but we cannot undermine or eliminate the use of $scope.
$scope is useful with $watch, $apply and broadcasting and listening to events using $broadcast, $on, $emit.

Declaration in different scenarios

General declaration

View or Html
<div ng-controller = "fooCtrl as foo">
    <button ng-click="foo.Action()">{{foo.title}}</button>
</div>
JavaScript – Controller
    app.controller('fooCtrl',[function(){
        this.title = "Click me!";
        this.Action = function(){
            alert('Who called me?')
        }
    }])

Declaring “controller as” in directive

JavaScript – Directive
app.directive('fooDir', function () {
  return {
    restrict: 'E',
    template: '<button ng-click="foo.Action()">{{foo.title}}</button>',
    controllerAs: 'foo', // refer controller using foo
    controller: function(){
        this.title = "Click me!";
        this.Action = function(){
            alert('Who called me?')
        }
    }
  };
});

Declaring “controller as” in UI router

JavaScript – ui-router
$stateProvider.state('home', {
   template: '<button ng-click="foo.Action()">{{foo.title}}</button>',
   controller: function(){
        this.title = "Click me!";
        this.Action = function(){
            alert('Who called me?')
        }
    }
  };
  controllerAs: 'foo'
});

Declaring “controller as” in Angular router

JavaScript – ngRoute
app.config(function ($routeProvider) {
  $routeProvider
  .when('/', {
    templateUrl: 'any view template url',
    controllerAs: 'foo', // refer controller using foo
    controller: 'fooCtrl' //name of your controller
  })
  .otherwise({
    redirectTo: '/'
  });
});

In all of above scenarios a better practice is to assign the “this” keyword to a variable and then use the variable to refer the controller.

var vm = this;

Generally developers tend to use “vm” which is considered as “view model”, but it won’t matter if you use any other.

Conclusion

It is a matter of personal preference which approach you would like to follow, however the gains from the “controller as” are too good to ignore. I personally prefer the “controller as” syntax over the classic $scope model.

About

Engineer. Blogger. Thinker. Loves programming and working with emerging tech. We can also talk on Football, Gaming, World Politics, Monetary Systems.

Get notified on our new articles

Subscribe and get AngularJS Tips PDF. We never spam!
First Name:
Email:

Leave a Comment