0

Just see the code

var angApp = angular.module('angApp',[]);  
angApp.controller('testController', ['$http', function ($http) {  
    var self = this;  
    self.name ='Hello';  

    self.btnClick=function(){  
        self.name ='Hello! Button Clicked';  
    }  
}]);  


<html>  
<head>  
</head>  
<body data-ng-app="angApp" data-ng-controller="testController as model">  
<div>  
    {{model.name}}  
    </br>  
    <input type="button" value="Click" data-ng-click="model.btnClick();"/>  
</div>  
</html>  

Now, tell me if we avoid scope and declare controller like this way testController as model then what will be an advantage or is it only syntactic sugar?

demongolem
  • 9,474
  • 36
  • 90
  • 105
Monojit Sarkar
  • 2,353
  • 8
  • 43
  • 94

2 Answers2

1

Basically, $scope has been removed as of Angular 2. In addition to that, the angular documentation specifically recommends using this instead of $scope.

Take a look at this article for more information: https://johnpapa.net/angularjss-controller-as-and-the-vm-variable/

And also check the accepted answer on this question: 'this' vs $scope in AngularJS controllers

Community
  • 1
  • 1
bamtheboozle
  • 5,847
  • 2
  • 17
  • 31
0

Once advantage I can think about is, if you have nested controllers, for instance

<div ng-controller="myFirstController as ctrl1">
    <div ng-controller="mySecondController as ctrl2">
        {{ctrl1.someValue}}
    </div>
</div>

It is easier and more clear when trying to reference a variable on the parent controller

Fraction
  • 463
  • 2
  • 11