Why You Should Use AngularJS's "Controller as" Syntax

Published Mar 30, 2017
Why You Should Use AngularJS's "Controller as" Syntax

What is this "Controller as" syntax?

AngularJS has become a popular front-end framework, which is why you've probably heard the term "controller as" thrown around a bit. This syntax is a way for us to access properties and methods of a controller declared on the controller via this. The support for this was introduced in AngularJS version 1.1.5.

Why should you use it?

Here are a few very good reasons:

  • When using nested scopes, it becomes completely clear where a method or property reference belongs to.
  • By not using $parent to access the properties of a parent controller, if things get moved, we can still be sure we are referencing the correct controller.
  • Because we are using dot notation, it becomes impossible to two-way bind to a primitive.

Example of NOT USING the "controller as" syntax

By not using the "Controller as" syntax, we can see things get complicated pretty quickly (imagine this in a very large application):

<div ng-app="app" ng-controller="SiteController">

  <!-- we are pretty sure we are getting the title from the SiteController -->
    <div ng-controller="PersonController">
        <!-- is this the title from SiteController or PersonController? 
        is there even a title in both? -->
    	<div ng-repeat="person in PersonCtrl.people">


Example of USING the "controller as" syntax

To use our "Controller as" syntax, first, we declare all of our properties and methods on the this property of our controller:

// site.controller.js:
(function() {

  'use strict';

  angular.module('app').controller('SiteController', SiteController);

  // no need to inject $scope because we don't need it
  SiteController.$inject = [];

  function SiteController() {
        // assigning this to a loacal variable makes it easier to 
        // declare properties and methods in the controller
    	var vm = this;
        // declare our title on this
        vm.title = "Welcome!";



// other.controller.js:
(function() {

  'use strict';

  angular.module('app').controller('OtherController', OtherController);

  function OtherController() {
    	var vm = this;
        vm.title = "Other title!";



Then things become a lot more visibile in the view. We can see where each bit of data is coming from:

<div ng-app="app" ng-controller="SiteController as SiteCtrl">

    <!-- we can be sure we are getting the title from the SiteController -->
    <div ng-controller="OtherController as OtherCtrl">
        <!-- we can be sure we are getting the title from the OtherCtrl -->


Here is a codepen to illustrate that. If you're just getting started with Angular JS, read this helpful guide: AngularJS Directives: A Beginner’s Practical Guide!

Happy coding 🎉

Discover and read more posts from Christopher Northfield
get started