我正在构建一个简单的庞多罗定时器,还处于学习角度的早期阶段。我在使用$scope.timeView变量每秒更新视图时遇到了问题。$scope.timeView每秒钟登录一次控制台,但不记录视图。我已经尝试过注入$interval并使用apply(),但它们无法工作。我相信这对训练有素的人来说是显而易见的,我会继续寻找的。在此期间,任何帮助都将不胜感激。谢谢。
pomodoro_timer.controller('app.controller', ['$scope', '$state', '$stateParams', function ($scope, $state, $stateParams) {
// (function() {
var intrvl;
var t = 1500;
var tDiv = $('#time');
$scope.startTimer = function() {
if (tDiv.hasClass("notWorking")) {
$scope.interval(t);
$scope.toggleClass();
}
};
$scope.interval = function() {
intrvl = setInterval(function(){
t -= 1;
$scope.displayTime(t)
},1000)
}
$scope.displayTime = function() {
var m = parseInt(t / 60);
var s = parseInt(t) % 60;
if (s < 10) {
s = "0" + s;
}
$scope.timeView = m+":"+s;
}
$scope.stopStart = function() {
if (tDiv.hasClass('working')) {
$scope.toggleClass();
clearInterval(intrvl);
$('#QwkBreak a').text('Continue Working'); //////////////////////Should I remove jQuery?/////////////////////////
} else if (t<1500) { // prevents timer from starting when '#QwkBreak' is clicked, unless timer has started counting down //
$('#QwkBreak a').text('Quick Break');
$scope.interval();
$scope.toggleClass();
}
}
$scope.toggleClass = function() {
tDiv.toggleClass('notWorking working');
}
$scope.resetTimer = function() {
if (!tDiv.hasClass('notWorking')) { //prevents reset button from toggling classes unless (class="working") //
clearInterval(intrvl);
t = 1500;
tDiv.text("25:00");
$scope.toggleClass();
}
}
// })();s
}]);
<body ng-controller="app.controller">
<h1>Pomodoro Timer</h1>
<div id="timeView">
<p id="time" class="notWorking">{{ timeView }}</p>
</div>
<div id="controls">
<button id="startWork"><a ng-click="startTimer()" href="#">Start Work</a></button>
<button id="QwkBreak"><a ng-click="stopStart()" href="#">Quick Break</a></button>
<button id="reset"><a ng-click="resetTimer()" href="#">Reset</a></button>
<button id="5_MInBreak">5-Min Break</button>
</div>
</div>发布于 2015-07-25 17:15:16
有$interval服务,内部将管理摘要,还允许使用cancel()方法轻松摆脱计时器。
$scope.interval = function() {
intrvl = $interval(function(){
t -= 1;
$scope.displayTime(t)
},1000)
}现在,您还希望在作用域被破坏时从窗口中移除该间隔计时器。
$scope.$on('$destroy', function(){
intrvl.cancel();
});您还需要在控制器中注入$interval。
还建议将所有与计时器相关的代码放在指令中。控制器中不应包含任何dom相关代码。
参考资料:$interval文档
https://stackoverflow.com/questions/31628980
复制相似问题