I am struggling with the concept of this
in angular. I've been reading the differences as explained very well in 'this' vs $scope in AngularJS controllers
but I have still issues whether this is useful in many cases at all.
I created a controller and a this.the_value
var
angular.module("TheApp", [])
.controller("TheCtrl", ["$scope", function($scope){
this.the_value = "Init value";
}]);
Now I like the concept here as I can write ng-controller="TheCtrl as myCtrl"
and reference the value in the view by myCtrl.the_value
.
I separate contexts when dealing with nested controllers, that's fine.
Then I realized I need to watch this variable via $scope.$watch
.
Now I either have to rewrite all my view code and move the_value to $scope
instead of this
so I can use
$scope.$watch("the_value", function(newValue, old ){
console.log("The old value: '"+old+"', the new value: '"+newValue+"'");
});
or do some nasty things like
$scope.$watch("myCtrl.the_value", function(newValue, old ){
console.log("This: The old value: '"+old+"', the new value: '"+newValue+"'");
});
which is evil as I am creating a dependency on my view alias of the controller name. If I refactor the view alias, this will break. (Even unit testing will get dirty with this dependency)
Does this
has a very very limited use, or am I getting something wrong? Everywhere where I initially started using this
turned into $scope
when I was adding new behaviour to the code.