Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: determine time elapsed, use to regularly update model and view

Context

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.

How I've (unsuccessfully) imagined it'd work:

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...

So I suppose, two questions:

  • How do you calculate time since pageload, as a callable function?
  • How do you recalculate the data model on a regular (per second) basis? Is $timeout a good method?
like image 298
yellow-saint Avatar asked Sep 21 '14 00:09

yellow-saint


2 Answers

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>

Example

like image 59
Josep Avatar answered Sep 22 '22 14:09

Josep


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);
like image 24
yellow-saint Avatar answered Sep 25 '22 14:09

yellow-saint