JS新手,如果不允许,将删除。我有一些常规的 JS 代码,我一直在尝试将其切换到 Controller 中。
对于给定的示例,最优化的方式是什么。我见过带有指令、计数器等的案例,但我认为这对于我正在做的事情来说非常复杂。到目前为止,我已经设法将秒和数十绑定(bind)到屏幕,但是我在更新 $interval 时遇到问题,我需要 .watch、.promises .then 吗? (抱歉,对于新手问题,任何帮助都会很棒)
JS脚本
window.onload = function() {
var seconds = 00;
var tens = 00;
var appendTens = document.getElementById("tens");
var appendSeconds = document.getElementById("seconds");
var buttonStart = document.getElementById('button-start');
var buttonStop = document.getElementById('button-stop');
var buttonReset = document.getElementById('button-reset');
var Interval;
buttonStart.onclick = function () {
clearInterval(Interval);
Interval = setInterval(startTimer, 10);
};
buttonStop.onclick = function () {
clearInterval(Interval);
};
buttonReset.onclick = function () {
clearInterval(Interval);
tens = "00";
seconds = "00";
appendTens.innerHTML = tens;
appendSeconds.innerHTML = seconds;
console.log("clear()");
};
function startTimer() {
tens++;
if (tens < 9) {
appendTens.innerHTML = "0" + tens;
}
if (tens > 9) {
appendTens.innerHTML = tens;
}
if (tens > 99) {
console.log("seconds");
seconds++;
appendSeconds.innerHTML = "0" + seconds;
tens = 0;
appendTens.innerHTML = "0" + 0;
}
if (seconds > 9) {
appendSeconds.innerHTML = seconds;
}
}
};
这就是我将 HTML 绑定(bind)到屏幕的方式
<span id="seconds">{{ seconds+":"+tens }}</span>
最佳答案
我使用一个简单的 $interval
循环来设置它,该循环更新秒和分钟:
angular.module('plunker', []).controller('MainCtrl', function($interval) {
var interval_;
this.seconds = 0;
this.minutes = 0;
this.start = function() {
interval_ = $interval(function() {
this.seconds++;
if(this.seconds > 59) {
this.seconds = 0;
this.minutes++;
}
}.bind(this), 1000)
}
this.stop = function() {
$interval.cancel(interval_)
}
})
.filter('adjustTime', function(){
return function(input) {
if(input < 10) {
return '0' + input;
}
return input;
}
});
我是委托(delegate)的粉丝,所以我制作了您看到的过滤器来处理添加额外的 0(如果小于 10);无需搞乱 $interval
逻辑。
关于javascript - 如何将普通 JS 秒表转换为 Angular 秒表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43825132/