The "Controller as" syntax

AngularJS 1.2 introduced the ability to namespace your controller methods using the "controller as" syntax. This allows you to abstract $scope in controllers and provide more contextual information in the template.

Getting ready

Suppose you had a simple application set up as follows:

(index.html)

<div ng-app="myApp">
  <div ng-controller="Ctrl">
    {{ data }}
  </div>
</div>

(app.js)

angular.module('myApp', [])
.controller('Ctrl', function($scope) {
  $scope.data = "This is string data";
});

How to do it…

The simplest way to take advantage of the "controller as" syntax is inside the ng-controller directive in a template. This allows you to namespace pieces of data in the view, which should feel good to you as more declarative views ...

Get AngularJS Web Application Development Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.