gpt4 book ai didi

javascript - AngularJS:确定耗时,用于定期更新模型和 View

转载 作者:数据小太阳 更新时间:2023-10-29 05:57:49 25 4
gpt4 key购买 nike

上下文

我想创建一个 Web 应用程序,该应用程序将一组数据视为自页面加载以来耗时的函数。想一想“自打开此网页以来,您燃烧了多少卡路里”。

我仍在努力思考 AngularJS 服务、工厂等,并想知道创建自动更新计时器的最佳方法是什么,该计时器可用于定期(每秒)操作和更新 ng-model .

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

我现在有这样的东西:

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>

Example

关于javascript - AngularJS:确定耗时,用于定期更新模型和 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25954539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com