How can I effectively listen to changes in my injected service within the controller? In the code example below, there are two instances of using $watch
- one that works but is unclear why, and another that seems intuitive but fails. Is the second approach correct? Could this lead to code duplication? What is the best practice for achieving this?
Service:
app.factory("StatsService", [
'$timeout', 'MockDataService',
function ($timeout, MockDataService) {
var service, timeout;
timeout = 5000;
service = {
fetch: function () {
// Irrelevant sample data fetching; triggers data update
return this.data = MockDataService.shuffle();
},
grab: function () {
this.fetch();
return this.update();
},
update: function () {
var _this = this;
return $timeout(function () {
return _this.grab();
}, timeout);
}
};
service.grab();
return service;
}
]);
Controller:
app.controller("StatsController", [
'$scope', 'StatsService',
function ($scope, StatsService) {
var chart;
$scope.stats = StatsService;
$scope.test = function (newValue) {
if (arguments.length === 0) {
return StatsService.data;
}
return StatsService.data = newValue;
};
// Below watch does not work
$scope.$watch('stats', function (stats) {
return console.log('meh');
});
// This watch works, for unknown reasons
$scope.$watch('test()', function (stats) {
return console.log('changed');
});
}
]);