What can be the reason to use "controllerAs" property?

Yes. A little more info:

Before the controllerAs syntax, methods and properties needed to be exposed to views by binding them to the $scope. With controllerAs, your controller instance is bound to the $scope as the property you select.

This way you can use Plain Old JavaScript Classes for your controllers.

Editorial: This is a much cleaner approach to development. One of the things that makes Angular so easy to write tests for is that your Controllers and components do not need to inherit from framework base-classes. See Backbone and Ember.

So with the old style your controllers would look like (in ES6 for simplicity):

YourController.$inject = ['$scope'];
class YourController {
  
    constructor($scope) {

        $scope.myMethod = () => { . . . };

        $scope.myProperty = true;
    }
}

With the controllerAs

class YourController {
  
    constructor() {

        this.myProperty = true;
    }

    myMethod() { . . . };
}

Just a plain old class rather than decorating or monkeypatching the $scope.


Few things:

1. Reduce scope usage

Instead of loading every data in the scope of a controller, you could simply use this to load up everything that you require.

eg:

Route

state('index',{
    url:"/",
    templateUrl:"views/index.html",
    controller:"ListCtrl",
    controllerAs:"list"
})

In Controller

angular.module('feed').controller('ListCtrl', function($scope, reddit){
    var vm   = this;
    vm.names = ["Michael", "Roy"];

});

In Template:

<ul>
    <li ng-repeat="name in list.names">
        <div>{{name}}</div>
    </li>
</ul>

2. Correct scope usage

When multiple controllers come into play, scope becomes a tricky thing. Using controllerAs method will go a long way is resolving this. An example is shown below:

Wrong:

<span>Outside Controller: Your name is: {{username}}</span>
<div ng-controller="SignupController">
    <span>Inside Controller: Your name is: {{username}}</span>
    <fieldset legend="User details">
        <input ng-model="username">
    </fieldset>
</div>

Correct:

<span>Outside Controller: Your name is: {{user.name}}</span>
<div ng-controller="SignupController">
    <span>Inside Controller: Your name is: {{user.name}}</span>
    <fieldset legend="User details">
        <input ng-model="user.name">
    </fieldset>
</div>

Found an image which makes everthing more clear:

enter image description here

Courtesy : AngularJs "controller as" syntax - clarification?

Tags:

Angularjs