How to watch a variable defined in a service in angularjs

zszep

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

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Java

How to deep watch an array in angularjs?

From Dev

Angularjs watch service object

From Dev

How to watch the DOM for changes AngularJS

From Dev

AngularJs watch window variable

From Dev

How to check if value service is already defined angularjs

From Dev

How to watch a primitive service variable in controller with AngularJS?

From Dev

AngularJS - how to handle circular watch?

From Dev

AngularJS watch variable in directive

From Dev

AngularJS pass variable to service

From Dev

AngularJS: $watch other service in a service

From Dev

How to access controller variable in service in AngularJS

From Dev

Service variable not updating in AngularJS

From Dev

how to watch a date object in angularJS

From Dev

How to watch for localstorage changes with AngularJS

From Dev

How to observe or watch an input attribute change in an AngularJS Service?

From Dev

how to read a variable inside service in angularjs?

From Dev

$watch a variable for change angularjs

From Dev

How to watch a promise in angularJS?

From Dev

How to watch a primitive service variable in controller with AngularJS?

From Dev

Accessing variable defined in slickgrid in AngularJs

From Dev

angularjs: $http is not defined in service

From Dev

AngularJS: $watch other service in a service

From Dev

How to access controller variable in service in AngularJS

From Dev

AngularJS : How to watch a service object

From Dev

How to call an AngularJS defined service method?

From Dev

variable not defined in AngularJS

From Dev

Pass a variable to a service with AngularJS?

From Dev

$scope is not defined in service AngularJs:

From Dev

AngularJS: Watch Service Property Changes

Related Related

HotTag

Archive