0

I am trying to watch changes on an json array defined in an angularj service, but when the change occures, the $watch function is not firing. My controller and service code goes as follows (plunker demo):

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope,cityService) {
  //$scope.cities = [];
  $scope.service = cityService;
  cityService.initCities();


  $scope.$watch('service.getCity()', function(newVal) {
    $scope.cities = newVal;
    console.log(newVal)
  });


});

app.service('cityService', function($http) {
  this.cities = [];

  this.initCities = function() {
      $http.get('data.js').success(function(data) {
          this.cities = data;
      });
  };

  this.getCity = function() {
      return this.cities;
  };
});
3
  • You can watch a function and not a variable. the function will be evaluaed in each digest. like this $scope.$watch(function() { return $scope.foo; }, function(newVal, oldVal) { console.log(newVal, oldVal); }); Commented Feb 1, 2014 at 11:57
  • Try to take a look stackoverflow.com/a/21460962/356380 Commented Feb 1, 2014 at 12:06
  • @Inu. Tried your suggestion, but it still doesn't work. See my plunker plnkr.co/edit/8g4Yf2wX7UBwThpy3Bvp?p=preview Commented Feb 1, 2014 at 12:11

2 Answers 2

2

This is because the callback from get set this to window object. Keep the reference of the service in self.

See this plunker http://plnkr.co/edit/CrgTWRBsg5wi7WOSZiRS?p=preview

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Seems I still have to improve on my javascript fundemantal skills. When you come from a C# background it sometimes gets really hard to get used to the way javascript handles scopes.
Yes the notorious javascript this
1

I changed several things to make it work: http://plnkr.co/edit/PDMaEvmx7hG1fKvAmR7R?p=preview

  • Function watch instead of variable
  • In the service, removed the keyword this because this has not the same context inside functions.
  • Return functions in service

Seems ok

1 Comment

Thanks for your help, it does work great, so I voted you up. But it seems that your comment that I have to use a function in the watch is not correct. I modified Chandermanis answer to use a variable instead of a function and it still is working correctly. So, it seems to me that Chandermani's answer is the correct one. plnkr.co/edit/8ey5u3NTBSNBDBOVMivn?p=preview

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.