i have factory manage standardized current time across app, has exposed function gettime().
i display on various pages; however, not updating minutes roll by. i'm trying below code in controller , expect once minute console log of current time, instead gets printed each time change page.
$scope.$watch(function () { return timeservice.gettime() }, function (newval, oldval) { if (typeof newval !== 'undefined') { console.log("$watch", newval); $scope.currenttime = newval; } }, true); how can watch return value of factory's function?
update
here timeservice code
var _gettime = function () { return _formattime(new date()); }; var _formattime = function (date) { var hours = date.gethours(); var minutes = date.getminutes(); var ampm = hours >= 12 ? 'pm' : 'am'; hours = hours % 12; hours = hours ? hours : 12; // hour '0' should '12' minutes = minutes < 10 ? '0'+minutes : minutes; var strtime = hours + ':' + minutes + ' ' + ampm; return strtime; };
there's no way angularjs can guess value of timeservice.gettime() changed. angular runs digest cycle responding things, user interaction, that's why works on page change. you'd need manually run $scope.$apply() fix this.
however, since need predictable change every 60 seconds, it'd better use $interval (https://docs.angularjs.org/api/ng/service/$interval) service:
$interval(function() { $scope.currenttime = timeservice.gettime() }, 60 * 1000) // runs every 60 seconds, or 60,000 milliseconds
Comments
Post a Comment