javascript - 使用 angularJS 服务将 `setInterval` 转换为 AngularJS

标签 javascript angularjs

我想将其转换为 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/

相关文章:

javascript - 所有数组元素均未分配给模型

javascript - 通过 Chrome 开发者工具查看来自 Ajax 调用的 HTML 响应?

javascript - HTML 和 Angular 中的动态变量?

csv - 如何将CSV文件加载到AngularJS中的对象?

angularjs - 在 Angular ui-router 中使用带有 $stateChangeStart toState 和 fromState 的 $state 方法

javascript - 热衷于使用 JavaScript 或 Jquery 从剑道下拉列表中获取值/文本对

javascript - 单击选择时如何更改选择的 "size"?

javascript - 将 meteor 调用的结果响应式(Reactive)添加到当前数据上下文

javascript - 日期倒计时不正确

javascript - 将路由参数传递给 Controller