我创建了一个倒计时时钟作为一个更大项目的一部分。这是该服务的代码
'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);
}
};
});
然后我从 Controller 调用它,该 Controller 也链接到 View
'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();
});
});
出于某种原因,我无法弄清楚如何将 secondaryRemaining 绑定(bind)到 $scope.seconds。我花了大约一个小时试图解决这个问题。我不完全是函数式编程的奇才,所以我有一种感觉,我只是想错了。
最佳答案
将 $interval
注入(inject)您的服务并用它替换 setInterval
:
timerProcess = $interval(this.timer, 1000);
如果你想使用观察者,你可以像这样注册它:
$scope.$watch(function () { return Countdownclock.getTime(); }, function (newValue, oldValue) {
// Might be identical when called due to initialization - Good to know for some cases
if (newValue !== oldValue) {
$scope.seconds = newValue;
}
});
关于javascript - 绑定(bind) Angular 服务进行查看,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22770915/