I'm looking to create a webapp that looks at a set of data as a function of time elapsed since pageload. Think "how many calories have you burnt since opening this webpage".
I'm still trying to wrap my head around AngularJS services, factories, etc, and was wondering what the best way to create an auto-updating Timer that could be used to regularly (per second) manipulate and update ng-model.
I've got something like this at the moment:
app.factory('Timer', function($timeout) {
var time = 0;
var Timer = function() {
this.time++;
this.timeout = $timeout(this.Timer, 1000);
}
});
And use as
$timeout(function() {
$scope.someNgModelVarForTheView = Timer.time * $scope.data;
}, 1000);
But... well. In my mind that works beautifully. In reality screw all happens, and I'm kidding myself if I know the right way to do this...
If you want to have your own service, you could do it like this:
.factory('MyTimer', function($interval){
return function(delay){
var initialMs= (new Date()).getTime();
var result = {totalMilliseconds:0, counts:0};
$interval(function() {
result.totalMilliseconds = (new Date()).getTime() - initialMs;
result.counts++;
}, delay);
return result;
};
})
And you could use it like this:
.controller('testController', function($scope, MyTimer){
$scope.t = MyTimer(1000);
});
And in your html you could do this:
<div ng-app="app" ng-controller="testController">
Total Ms: {{t.totalMilliseconds}}
Counts: {{t.counts}}
</div>
Eh, I ended up overcomplicating my thoughts. This did the trick:
var delay = 1000; // 1 sec
$scope.currentTime = 0;
$interval(function() {
$scope.currentTime += delay;
$scope.someData *= $scope.currentTime;
}, delay);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With