我创建了一个倒计时时钟作为大型项目的一部分。下面是服务绑定角度服务查看
'use strict';
angular.module('myApp')
.service('Countdownclock', function Countdownclock() {
var secondsRemaining = 0;
var timerProcess;
return {
//initialize the clock
startClock: function(minutes) {
secondsRemaining = minutes * 60;
timerProcess = setInterval(this.timer, 1000);
},
//timer function
timer: function() {
secondsRemaining -= 1;
if (secondsRemaining <= 0) {
clearInterval(timerProcess);
}
},
//get time
getTime: function() {
return secondsRemaining;
},
//add time
addTime: function(seconds) {
secondsRemaining += seconds;
},
//stop clock
stopClock: function() {
secondsRemaining = 0;
clearInterval(timerProcess);
}
};
});
然后我调用它的从控制器,该控制器还链接到一个视图
'use strict';
angular.module('myApp')
.controller('MainCtrl', function($scope, Countdownclock) {
Countdownclock.startClock(1);
$scope.seconds = Countdownclock.getTime();
$scope.$watch(Countdownclock.getTime(), function(seconds) {
$scope.seconds = Countdownclock.getTime();
});
});
出于某种原因,我无法弄清楚如何绑定secondsRemaining代码到$ scope.seconds。我一直在试图弄清楚这个事情大概一个小时。我在功能编程上并不完全是一个智者,所以我有一种感觉,我只是在想它是错的。
你不应该使用setInterval或clearInterval方法。使用Angular等价物。抱歉在移动设备上,这限制了我的写作。请稍后再试看看 – Spock
试试$ scope。$ watch('seconds',..... – Whisher