Monojit Sarkar
Monojit Sarkar

Reputation: 2451

What is the advantage of controller without scope?

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?

Upvotes: 0

Views: 59

Answers (2)

Fraction
Fraction

Reputation: 463

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

Upvotes: 0

bamtheboozle
bamtheboozle

Reputation: 6436

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

Upvotes: 1

Related Questions