AngularJS Why ControllerAs Syntax ?


Example

Controller Function

Controller function is nothing but just a JavaScript constructor function. Hence, when a view loads the function context(this) is set to the controller object.

Case 1 :

this.constFunction = function() { ... }

It is created in the controller object, not on $scope. views can not access the functions defined on controller object.

Example :

<a href="#123" ng-click="constFunction()"></a> // It will not work

Case 2 :

$scope.scopeFunction = function() { ... }

It is created in the $scope object, not on controller object. views can only access the functions defined on $scope object.

Example :

<a href="#123" ng-click="scopeFunction()"></a> // It will work

Why ControllerAs ?

  • ControllerAs syntax makes it much clearer where objects are being manipulated.Having oneCtrl.name and anotherCtrl.name makes it much easier to identify that you have an name assigned by multiple different controllers for different purposes but if both used same $scope.name and having two different HTML elements on a page which both are bound to {{name}} then it is difficult to identify which one is from which controller.

  • Hiding the $scope and exposing the members from the controller to the view via an intermediary object. By setting this.*, we can expose just what we want to expose from the controller to the view.

      <div ng-controller="FirstCtrl">
          {{ name }}
          <div ng-controller="SecondCtrl">
              {{ name }}
              <div ng-controller="ThirdCtrl">
                  {{ name }}
              </div>
          </div>
      </div>
    

Here, in above case {{ name }} will be very confusing to use and We also don't know which one related to which controller.

<div ng-controller="FirstCtrl as first">
    {{ first.name }}
    <div ng-controller="SecondCtrl as second">
        {{ second.name }}
        <div ng-controller="ThirdCtrl as third">
            {{ third.name }}
        </div>
    </div>
</div>

Why $scope ?

  • Use $scope when you need to access one or more methods of $scope such as $watch, $digest, $emit, $http etc.
  • limit which properties and/or methods are exposed to $scope, then explicitly passing them to $scope as needed.