Reputation: 4458
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
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
Reputation: 1414
I changed several things to make it work: http://plnkr.co/edit/PDMaEvmx7hG1fKvAmR7R?p=preview
Seems ok
Upvotes: 1