AngularJS Simple - Controller As Syntax
by Matthew Day
HTML
<div ng-app="myApp">
<div ng-controller="ParentCtrl as parent">
{{parent.name}} is thirty years old.
<div ng-controller="ChildCtrl as child">
{{parent.name}} is the father of {{child.name}}, who is seven years old.
</div>
</div>
</div>
JavaScript
angular.module('myApp', [])
.controller('ParentCtrl', function() {
var parent = this;
parent.name = 'William';
})
.controller('ChildCtrl', function() {
var child = this;
child.name = 'Henry';
})
/*
Implementing a 'Controller As' syntax is especially useful when controllers are nested. When this happens, their respective scopes may be somewhat difficult to follow.
Although this example here uses the same variable names in the controller as well as the HTML (e.g. 'parent' and 'child'), it is not necessary that they share the same variable names.
Also, we have removed the variable which stored the angular module (previous iterations of this fiddle have "var app = angular.module('myApp', [])"). This is done in order to avoid declaring a global variable and also because 'angular.module' already lives in the global scope.
*/