First of all, I apologize for the long and incredibly confusing title, but I was told that it is not polite to post questions with clickbait-y titles like "what's the difference between these two approaches", even though that would've been more appropriate in this case.
Anyhow, I was studying Angular and realized that there are two ways of creating variables:
- The first one of them is by passing $scope as a parameter to the controller function, and make $scope.variable = 5, for example. Like this:
angular.module("ex").controller("ExCtrl", function($scope){
$scope.variable = 5;
});
And, in the HTML page, just make:
<div ng-controller="ExCtrl">{{variable}}</div>
- You can also make the variable local to the controller, like this:
angular.module("ex").controller("ExCtrl", function($scope){
var self = this;
self.variable = 5;
});
And, in the HTML page, just make:
<div ng-controller="ExCtrl as exc">{{exc.variable}}</div>
My question is: what are the key differences between these approaches? I suppose the place where the variable is stored is different between the two, with it being local to the scope in the first and being local to the controller in the second. Is that right? If it is, is there any other difference? Why would someone favor one over the other? And if it is not right, what are the differences then?
Thank you in advance.