Angular1 Controller As


// Angular 1 - The "controller as" syntax:

The "controller as" syntax was added in version 1.2.  It eliminates the need for 
scope in many instances.  That is valuable because scope hierarchy can often 
cause problem related to the prototypical inheritance and their primitive 
variables as we mentioned elsewhere.  The "controller as" syntax also provides 
a better way to view relationships between parents and children.

To use the "controller as" syntax, first remove references to '$scope'.  If we 
are going to use advanced features like watchers, then we will still need to use 
$scope.  When using the "controller as" syntax, instead of using $scope, we 
attach all of our variables and methods that we want to expose to the HTML onto 

With the "controller as" syntax, we are able to use the same variable name for 
all of our controllers because the "controller as" syntax is going to manage 
the dot notation for us, and therefore eliminate the "scope shadowing" issue.

app.controller('ParentController', [function() {
  this.message = 'Hello from parent.';

app.controller('FirstChild', [function() {
  this.message = 'Hello from first child.';

app.controller('SecondChild', [function() {
  this.message = 'Hello from second child.';

  <div ng-controller="ParentController as parent">
    <p>This is the parent: {{parent.message}}</p>

    <div ng-controller="FirstChild as first">
      <p>This is the parent: {{parent.message}}</p>
      <p>This is the first child: {{first.message}}</p>

    <div ng-controller="SecondChild as second">
      <p>This is the parent: {{parent.message}}</p>
      <p>This is the second child: {{second.message}}</p>

So, to use the "controller as" syntax, we:

1. Remove $scope from our controller functions.  Notice that
   we now use the this keyword inside our controller function.
2. Update the ng-controller attributes in our HTML to use 
   ng-controller="... as variableName"
3. Update our HTML to use {{variableName.variableName}}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License