AngularJS:确定经过的时间,用于定期更新模型和视图

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

本文关键字:定期更新 用于 模型 视图 时间 经过 AngularJS      更新时间:2023-09-26

上下文

我想创建一个网络应用程序,它将一组数据视为页面加载后经过的时间的函数。想想"自从打开这个网页以来,你燃烧了多少卡路里"。

我仍在努力了解AngularJS服务、工厂等,并想知道创建一个可用于定期(每秒)操作和更新ng模型的自动更新定时器的最佳方法是什么。

我是如何(没有成功)想象它会起作用的:

我现在有这样的东西:

app.factory('Timer', function($timeout) {
    var time = 0;
    var Timer = function() {
        this.time++;
        this.timeout = $timeout(this.Timer, 1000);
    }
});

并用作

$timeout(function() {
    $scope.someNgModelVarForTheView = Timer.time * $scope.data;
}, 1000);

但是。。。好在我看来,这很好用。事实上,一切都是一团糟,如果我知道正确的方法,我是在开玩笑。。。

所以我想,有两个问题:

  • 作为一个可调用函数,如何计算自页面加载以来的时间
  • 如何定期(每秒)重新计算数据模型?$timeout是个好方法吗

如果你想拥有自己的服务,你可以这样做:

.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;
    };
 })    

你可以这样使用它:

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

在你的html中,你可以这样做:

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

示例

呃,我的想法太复杂了。这就成功了:

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