tzortzik
tzortzik

Reputation: 5133

watch cannot see the changed variable from a service

I have the following piece of code

angular.module('plunker', []);

angular.module('plunker').service('MyService', function () {
  this.myVar = null;

  this.setX = function() {
    this.myVar = 'x';
   };
});

angular.module('plunker').controller('ctrl', function($scope, $timeout, MyService){

  $scope.myService = MyService;

 $scope.$watch('myService.myVar', function(newval, oldval) {
   console.log(newval, oldval);
 });

  $scope.setX = MyService.setX;

 $timeout(function() {
   $scope.setX()
 }, 1000);


}); 

Please note the assignment $scope.setX = MyService.setX;.

When it logs in console, it prints only null null. The expected result should be

null null
x null

Why is this happening?

Upvotes: 2

Views: 46

Answers (1)

Joao Polo
Joao Polo

Reputation: 2163

Your function at service is overlapping the this variable. Try to store the "this" variable:

angular.module('plunker').service('MyService', function () {
    var self = this;

    self.myVar = null;

    self.setX = function() {
        self.myVar = 'x';
    };
});

And optionally, try to use the function watch format:

$scope.$watch(function() { return  $scope.myService.myVar; },
    function(newval, oldval) {
        console.log(newval, oldval);
    }
);

Upvotes: 2

Related Questions