如何在AngularJS和HTML中制作滴答时钟(时间)

时间:2014-04-30 08:28:37

标签: html angularjs time clock

我是一名初学者AngularJS / html用户,他一直试图找到一个代码段来为网络应用制作时钟/时间项目。

网络搜索没有提供直截了当的结果,就像我期望它们那么简单,所以我想我会发布这个问题来获得一些答案,并让其他人更容易找到。

我已经发布了我的解决方案但是想在选择答案之前看看有没有更好的东西!

8 个答案:

答案 0 :(得分:53)

试图改善亚美尼亚的答案。您可以使用$interval服务设置计时器。

var module = angular.module('myApp', []);

module.controller('TimeCtrl', function($scope, $interval) {
  var tick = function() {
    $scope.clock = Date.now();
  }
  tick();
  $interval(tick, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular.min.js"></script>

<div ng-app="myApp">
  <div ng-controller='TimeCtrl'>
    <p>{{ clock | date:'HH:mm:ss'}}</p>
  </div>
</div>

答案 1 :(得分:38)

这对我很有效,我认为很容易跟随新手。查看行动here

<强> JavaScript的:

function TimeCtrl($scope, $timeout) {
    $scope.clock = "loading clock..."; // initialise the time variable
    $scope.tickInterval = 1000 //ms

    var tick = function() {
        $scope.clock = Date.now() // get the current time
        $timeout(tick, $scope.tickInterval); // reset the timer
    }

    // Start the timer
    $timeout(tick, $scope.tickInterval);
}

<强> HTML:

<div ng-controller='TimeCtrl'>
    <p>{{ clock  | date:'medium'}}</p>
</div>

不要忘记包含angularJS和&#39; ng-app&#39;在你的身体标签。

答案 2 :(得分:2)

这是我使用$interval提出的最简单的答案:

<强> Example

JS

grep

HTML

function TimeCtrl($interval) {
     var timeController = this;

     timeController.clock = { time: "", interval: 1000 };

     $interval(function () { 
         timeController.clock.time = Date.now();}, 
         timeController.clock.interval);
}

这是一个定时器实现,使用相同的$ interval注册函数在启动时注册新的间隔,并在停止时取消间隔。

警告!无法绑定到$ interval delay参数

<强> Example

JS

<div ng-controller='TimeCtrl as timeCtrl'>
    <p>{{ timeCtrl.clock.time | date:'medium'}}</p>
</div>

HTML

function TimeCtrl($interval) {

    var timeController = this;

    timeController.clock = { time: "", interval: 1000 };

    timeController.timer = { time: (new Date()).setHours(0,0,0,0), startTime: "", interval: 10};

    timeController.timerProcess;

    timeController.timerStart = function() {
      // Register the interval and hold on to the interval promise
      timeController.timerProcess = RegisterInterval(TimerTick, timeController.timer.interval);
      // Reset the time to 0
      timeController.timerReset();
    }

    timeController.timerReset = function() {
      timeController.timer.startTime = Date.now();
      timeController.timer.time = (new Date()).setHours(0,0,0,0); 
    }

    timeController.timerStop = function() {
        // If there is an interval process then stop it
        if(timeController.timerProcess){
        $interval.cancel(timeController.timerProcess);
      }
    }

    function ClockTick() { 
        timeController.clock.time = Date.now();
    }

    function TimerTick(){
      // Increment the time by the time difference now and the timer start time
      timeController.timer.time += Date.now() - timeController.timer.startTime;
      // Reset the start time
      timeController.timer.startTime = Date.now();
    }

    function RegisterInterval(regFunction, regInterval){
      return $interval(regFunction, regInterval);
    } 

    RegisterInterval(ClockTick, timeController.clock.interval);
}

答案 3 :(得分:2)

我创建了一个小指令来显示数字时钟。需要自调用功能,因为渲染时钟时会有一秒钟的延迟。

var app = angular.module('clock', []);

app.directive("digitalClock", function($timeout, dateFilter) {
  return {
    restrict: 'E',
    link: function(scope, iElement) {
      (function updateClock() {
        iElement.text(dateFilter(new Date(), 'H:mm:ss'));
        $timeout(updateClock, 1000);
      })();
    }
  };
});
<!DOCTYPE html>
<html ng-app="clock">

<head>
  <meta charset="utf-8" />
  <title>Digital clock</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>

<body>
  <h1 class="text-center">Digital Clock</h1>
<digital-clock></digital-clock>
</body>

</html>

答案 4 :(得分:1)

如何使用Angular文档中的间隔来实现此目的example。你也可以用plunker试试。

以下是代码:

<强>使用Javascript:

<script>
  angular.module('intervalExample', [])
    .controller('ExampleController', ['$scope', '$interval',
      function($scope, $interval) {
        $scope.format = 'M/d/yy h:mm:ss a';
        $scope.blood_1 = 100;
        $scope.blood_2 = 120;

        var stop;
        $scope.fight = function() {
          // Don't start a new fight if we are already fighting
          if ( angular.isDefined(stop) ) return;

          stop = $interval(function() {
            if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
              $scope.blood_1 = $scope.blood_1 - 3;
              $scope.blood_2 = $scope.blood_2 - 4;
            } else {
              $scope.stopFight();
            }
          }, 100);
        };

        $scope.stopFight = function() {
          if (angular.isDefined(stop)) {
            $interval.cancel(stop);
            stop = undefined;
          }
        };

        $scope.resetFight = function() {
          $scope.blood_1 = 100;
          $scope.blood_2 = 120;
        };

        $scope.$on('$destroy', function() {
          // Make sure that the interval is destroyed too
          $scope.stopFight();
        });
      }])
    // Register the 'myCurrentTime' directive factory method.
    // We inject $interval and dateFilter service since the factory method is DI.
    .directive('myCurrentTime', ['$interval', 'dateFilter',
      function($interval, dateFilter) {
        // return the directive link function. (compile function not needed)
        return function(scope, element, attrs) {
          var format,  // date format
              stopTime; // so that we can cancel the time updates

          // used to update the UI
          function updateTime() {
            element.text(dateFilter(new Date(), format));
          }

          // watch the expression, and update the UI on change.
          scope.$watch(attrs.myCurrentTime, function(value) {
            format = value;
            updateTime();
          });

          stopTime = $interval(updateTime, 1000);

          // listen on DOM destroy (removal) event, and cancel the next UI update
          // to prevent updating time after the DOM element was removed.
          element.on('$destroy', function() {
            $interval.cancel(stopTime);
          });
        }
      }]);
</script>

<强> HTML

<div>
  <div ng-controller="ExampleController">
    <label>Date format: <input ng-model="format"></label> <hr/>
    Current time is: <span my-current-time="format"></span>
    <hr/>
    Blood 1 : <font color='red'>{{blood_1}}</font>
    Blood 2 : <font color='red'>{{blood_2}}</font>
    <button type="button" data-ng-click="fight()">Fight</button>
    <button type="button" data-ng-click="stopFight()">StopFight</button>
    <button type="button" data-ng-click="resetFight()">resetFight</button>
  </div>
</div>

结果如下: enter image description here

答案 5 :(得分:1)

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval) {
    $scope.theTime = new Date().toLocaleTimeString();
    $interval(function () {
        $scope.theTime = new Date().toLocaleTimeString();
    }, 1000);
});

答案 6 :(得分:0)

您可以使用此代码。它更简单。

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="clockApp">
    <head>
        <script src="../angular.js"></script>
    </head>
    <body>
        <h1> Clock App </h1>
        <div ng-controller="MainCtrl">
            <p> The current time is : {{timeString}}</p>
        </div>

        <script>
          var module = angular.module("clockApp", []);
          module.controller("MainCtrl", TimeCtrl);     

                    function TimeCtrl($scope){
                         var currentDate = new Date();
                        $scope.timeString = currentDate.toTimeString();                        
                    }
       </script>
    </body>
</html>
&#13;
&#13;
&#13;

答案 7 :(得分:-1)

执行此操作的最佳方法是使用“可观察的间隔”:

this.now = interval(1000).pipe(timestamp(), map(t => new Date(t.timestamp)));

然后使用异步和日期管道显示数据:

Now: {{ this.now | async | date: 'mediumTime' }}