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

Context

I am looking to create a webapp that looks at a dataset as a function of the time elapsed since pageload started. Think about how many calories you've burned since opening this web page.

I'm still trying to wrap my head around AngularJS services, factories, etc., and wondered what is the best way to create an automatic timer update that could regularly (per second) manipulate and update the ng-model.

As I (unsuccessfully) suggested this would work:

I have 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 good. In my opinion, this works great. Actually screw everything happens, and I'm joking if I know the right way to do this ...

So, I suppose two questions:

  • How do you calculate time with pageload as a function of a call?
  • How do you recalculate the data model on a regular basis (per second)? Is $ timeout a good method?
+5
source share
2 answers

If you want to have your own service, you can do it as follows:

 .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 can use it as follows:

 .controller('testController', function($scope, MyTimer){ $scope.t = MyTimer(1000); }); 

And in your html you can do this:

 <div ng-app="app" ng-controller="testController"> Total Ms: {{t.totalMilliseconds}} Counts: {{t.counts}} </div> 

Example

+8
source

Eh, I finished embarrassing my thoughts. This did the trick:

 var delay = 1000; // 1 sec $scope.currentTime = 0; $interval(function() { $scope.currentTime += delay; $scope.someData *= $scope.currentTime; }, delay); 
+1
source

Source: https://habr.com/ru/post/1203057/


All Articles