Skip to main content

ControllerAs Syntax in AngularJS - Best Practice

Here we will learn why we need ControllerAs in angularjs

All we know communication between controller and View happens via $scope.

Let have a code below

AngularJS:

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstname = "Devesh";

});
</script>


HTML :

<div ng-app="myApp" ng-controller="myCtrl">
    Name: <input ng-model="firstname">
    <h1>{{firstname}}</h1>
</div>



Here we have few issues

1. Binding everything to $scope, will increase  watch list of the $digest loop. which will cause performance issue so angularJs include ControllerAs syntax.


ControllerAs syntax

AngularJS:

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    this.firstname = "Devesh";

});
</script>

HTML 

<div   ng-app="myApp"  ng-controller="MyCtrl as mctrl">
  <h1 ng-bind="mctrl.firstname "></h1>
</div>


here we are not using $scope and we are using  ng-controller="MyCtrl as mctrl"

and mctrl.firstname to access the data.

2. Second Problem :  look at code below

AngularJs

<script>
var app = angular.module('myApp', []);
app.controller('ParentCntrl', function($scope) {
    $scope.firstname = "Devesh";

});

app.controller('ChildCntrl', function($scope) {
    $scope.firstname = "Devesh2";

});

app.controller('NestedCntrl', function($scope) {
    $scope.firstname = "Devesh3";

});
</script>


Explanation :

We have defined 3 controllers ParentCntrl,ChildCntrl,NestedCntrl
and having  $scope.firstname in each controller

HTML :

<div ng-controller="ParentCntrl">
  {{ firstname }}
  <div ng-controller="ChildCntrl">
    {{ firstname }}
    <div ng-controller="NestedCntrl">
      {{ firstname }}
    </div>
  </div>
</div>

Here in above HTML we are printing firstname at each div
but here code appeard bad as it appears we are printing firstname but for which controller, code is confusing so it is bad
Practice


Solution :

instead having $scope try to use "this" in controller and use controllerAs syntax

HTML:

<div ng-controller="ParentCntrl as P1">
  {{ P1.firstname }}
  <div ng-controller="ChildCntrl as C1">
    {{ C1.firstname }}
    <div ng-controller="NestedCntrl as n1">
      {{ n1.firstname }}
    </div>
  </div>
</div>

Here in above HTML we can easily identify the relation between each controller. code is clear and easy to understand

Comments

Contact Form

Name

Email *

Message *