我想将其转换为 AngularJS,但我不知道从哪里开始
// Set the date we're counting down to
var countDownDate = new Date("Oct 1, 2022 15:37:25").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
$('#clock-days').text(days);
$('#clock-hours').text(hours);
$('#clock-minutes').text(minutes);
$('#clock-seconds').text(seconds);
}, 1000);
第一个问题是Math函数不可用,interval怎么写?
最佳答案
您可以在 Controller 中将 setInterval
替换为 $interval
,然后将 var 变量更改为范围变量,请研究下面的 fiddle 以找出差异。
演示:JSFiddle
var app = angular.module('myApp', []);
app.controller('MyController', ['$scope', '$interval', function($scope, $interval) {
var countDownDate = new Date("Oct 1, 2022 15:37:25").getTime();
// Update the count down every 1 second
var x = $interval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
$scope.days = Math.floor(distance / (1000 * 60 * 60 * 24));
$scope.hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
$scope.minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
$scope.seconds = Math.floor((distance % (1000 * 60)) / 1000);
}, 1000);
}]);
关于javascript - 使用 angularJS 服务将 `setInterval` 转换为 AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45892974/