AngularJS - Experimental "Controller as" Syntax

AngularJS 1.1.5 introduced support for “Controller as” syntax. This syntax can impact the way you think about angular. We can now define a named scope for a controller with the ng-controller directive, for example “RoomCtrl as room”, where room is the named scope:

<div ng-app="app" ng-controller="RoomCtrl as room">

</div>

Let’s create our room controller without a scope, so instead of defining functions on the $scope, we define it on “this” within the function. We’ll create the openDoor function on “this” and alert “creak”

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

app.controller("RoomCtrl", function(){
  this.openDoor= function(){
    alert("creak");
  };
});

Now we can access the room controller in our app by using “room”. Let’s create a button with the text of “open” and ng-click as “room.openDoor()”. “room” refers to the RoomCtrl scope we created in our directive.

<div ng-app="app" ng-controller="RoomCtrl as room">
  <div class="button" ng-click="room.openDoor()">
    Open
  </div>
</div>

When we load the page and click the button the we will be alerted with “creak”. We did this without manipulating the $scope object at all, we defined the function on “this”. We can also do this with text, setting “buttonTitle” on “this” to “I’m a button” and then creating a binding using the named scope on our button “room.buttonTitle”:

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

app.controller("RoomCtrl", function(){
  this.openDoor= function(){
    alert("creak");
  };

  this.buttonTitle = "I'm a button";
});
<div ng-app="app" ng-controller="RoomCtrl as room">
  <div class="button" ng-click="room.openDoor()">
    {{room.buttonTitle}}
  </div>
</div>

Now we put into the controller we can put into the html itself by defining things on the function instead of the scope, which could potentially be useful for other languages like coffeescript where you can define classes and expose functions and use those as your controllers

The scope can still be really useful for watchers, $apply, and scope inheritance, but using the “Controller as ” syntax we can directly expose things to our HTML through the controller. This used to be achievable before the “Controller as ” syntax doing something like:

  $scope.room = this;

assuming we had $scope injected into our controller.

This new syntax also helps as we start to get into nested controllers. The named scopes are clearly defined so there won’t be conflicts between controllers since you must state which controller you’re referencing before the “dot”. This feature is still experimental.