zszep
zszep

Reputation: 4458

How to watch a variable defined in a service in angularjs

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;
  };
});

Upvotes: 0

Views: 957

Answers (2)

Chandermani
Chandermani

Reputation: 42669

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

Upvotes: 2

lnu
lnu

Reputation: 1414

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

Upvotes: 1

Related Questions