How to make a ticking clock (time) in AngularJS an

2019-01-08 13:39发布

I'm a beginner AngularJS/html user who's been trying to find a code snippet to make a clock/time item for a web app.

A web search did not provide straight-forward results as easily as I would expect them for something so trivial, so I thought I would post this question to get some answers and also make this easier to find for others.

I have posted my solution but want to see if there is anything nicer out there before choosing an answer!

7条回答
手持菜刀,她持情操
2楼-- · 2019-01-08 14:01

Just trying to improve Armen's answer. You can use the $interval service to setup a timer.

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>

查看更多
成全新的幸福
3楼-- · 2019-01-08 14:03

I created a small directive to display a digital clock. The self invoking function is needed because there would be one second delay when rendering the clock.

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楼-- · 2019-01-08 14:06

This works quite nicely for me and I think is easy to follow for noobs. See it in action 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>

Don't forget to include angularJS and the 'ng-app' in your body tag.

查看更多
够拽才男人
5楼-- · 2019-01-08 14:06

This is the simplest answer I could come up with using $interval:

Example

The JS

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

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

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

The HTML

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

Here is a timer implementation using the same $interval registration function to register a new interval on start, and cancel the interval on stop.

WARNING! It is not possible to bind to the $interval delay parameter

Example

The JS

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);
}

The HTML

<div ng-controller='TimeCtrl as timeCtrl'>
    <p>Date: {{ timeCtrl.clock.time | date:'medium'}}</p>
     <p>Timer: {{ timeCtrl.timer.time | date:'mm:ss:sss'}}</p>
     <button type="button" ng-click="timeCtrl.timerStart()">Start</button>
     <button type="button" ng-click="timeCtrl.timerReset()">Reset</button>
     <button type="button" ng-click="timeCtrl.timerStop()">Stop</button>
</div>
查看更多
甜甜的少女心
6楼-- · 2019-01-08 14:18
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval) {
    $scope.theTime = new Date().toLocaleTimeString();
    $interval(function () {
        $scope.theTime = new Date().toLocaleTimeString();
    }, 1000);
});
查看更多
7楼-- · 2019-01-08 14:23

You can use this code. It's more simple.

<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>

查看更多
登录 后发表回答