我面临一个非常奇怪的问题,我使用角度js创建秒表,我使用以下代码更新计时器。
$scope.seconds = $scope.minutes = $scope.hours = "00";
$scope.timer = {
h: 0,
m: 0,
s: 0
};
$scope.runTimer = function() {
console.log($scope.timer);
$scope.timer.s++;
if ($scope.timer.s >= 60) {
$scope.timer.s = 0;
$scope.timer.m++;
if ($scope.timer.m >= 60) {
$scope.timer.m = 0;
$scope.timer.h++
}
}
$scope.seconds = $scope.timer.s > 9 ? "" + $scope.timer.s : "0" + $scope.timer.s;
$scope.minutes = $scope.timer.m > 9 ? "" + $scope.timer.m : "0" + $scope.timer.m;
$scope.hours = $scope.timer.h > 9 ? "" + $scope.timer.h : "0" + $scope.timer.h;
$scope.continueTimer();
};
$scope.continueTimer = function() {
setTimeout($scope.runTimer, 1000);
};
但问题是范围变量的值seconds
,minutes
& hours
仅在视图中第一次更新,即runTimer
方法由ng-click
触发,因此模板从00:00:00
更改为00:00:01
,并且然后不更新..
使用控制台,我检查了$scope.seconds
,$scope.minutes
&的价值。 $scope.hours
正在正确更新,但视图未反映正确的值。
这是plunker,显示我面临的确切问题。任何帮助将不胜感激。感谢。
答案 0 :(得分:3)
使用$scope.$digest()
并在!$scope.$$phase
$scope.$digest()
if(!$scope.$$phase)
{
$scope.$digest();
}
因此,您的app.js
文件代码应该类似于
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.seconds = $scope.minutes = $scope.hours = "00";
$scope.timer = {
h: 0,
m: 0,
s: 0
};
$scope.runTimer = function() {
console.log($scope.timer);
$scope.timer.s++;
if ($scope.timer.s >= 60) {
$scope.timer.s = 0;
$scope.timer.m++;
if ($scope.timer.m >= 60) {
$scope.timer.m = 0;
$scope.timer.h++
}
}
$scope.seconds = $scope.timer.s > 9 ? "" + $scope.timer.s : "0" + $scope.timer.s;
$scope.minutes = $scope.timer.m > 9 ? "" + $scope.timer.m : "0" + $scope.timer.m;
$scope.hours = $scope.timer.h > 9 ? "" + $scope.timer.h : "0" + $scope.timer.h;
**if(!$scope.$$phase)
{
$scope.$digest();
}**
$scope.continueTimer();
};
$scope.continueTimer = function() {
setTimeout($scope.runTimer, 1000);
};
});
查看此工作plunker