0

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.

Community
  • 1
  • 1
Samuel
  • 6,126
  • 35
  • 70

2 Answers2

1

If you are using this, you can watch first level variables passing a function as first parameter to $scope.$watch

$scope.watch(

  function() {
    return this.the_value; //this is the real variable to be watched
  }.bind(this), //binding allows to use 'this' inside function

  function(newVal, oldVal) {
    console.log(newVal, oldVal); //this is the callback
  }

);
alberto-bottarini
  • 1,213
  • 9
  • 21
0

The easy fix for this is to watch a function that returns the variable observed.

Wrapping the variable will allow you to use this and not require you to use the controllerAs alias.

$scope.$watch(function() {
  return that.the_value

}, function(newValue, old) {
  console.log("This: The old value: '" + old + "', the new value: '" + newValue + "'");
});
AviG
  • 161
  • 4
  • @tarini posted the correct answer. You have a typo, you are using that instead of this but even with that a proper bind is necessary in order for the example to work. – Samuel Jul 28 '15 at 10:59
  • I had declared var that=this to avoid any closure issues. – AviG Jul 28 '15 at 11:12