2014-04-30 43 views
29

Tôi là người dùng AngularJS/html mới bắt đầu tìm kiếm đoạn mã để tạo mục đồng hồ/thời gian cho ứng dụng web.Cách tạo đồng hồ bấm giờ (thời gian) trong AngularJS và HTML

Tìm kiếm trên web không cung cấp kết quả thẳng đến dễ dàng như tôi mong đợi cho một thứ gì đó tầm thường, vì vậy tôi nghĩ tôi sẽ đăng câu hỏi này để nhận được một số câu trả lời và cũng dễ dàng hơn.

Tôi đã đăng giải pháp của mình nhưng muốn xem liệu có điều gì đẹp hơn ở ngoài đó trước khi chọn câu trả lời không!

Trả lời

37

Điều này làm việc khá độc đáo đối với tôi và tôi nghĩ là dễ làm theo cho noobs. Nhìn thấy nó trong hành động 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> 

Đừng quên bao gồm angularJS và 'ng ứng dụng' trong thẻ cơ thể của bạn.

+14

này có thể đạt được tao nhã hơn khi sử dụng khoảng $. –

+0

Tôi có một số câu hỏi: Tại sao không bắt đầu bằng cách sử dụng chỉ cần đánh dấu(); và tại sao sử dụng phạm vi và không phải cái gì đó liếm var time = this ;? – olahell

+1

Bạn cũng nên chỉ sử dụng một chỉ thị để làm điều đó và có thể làm một cái gì đó như: '' – OpensaurusRex

1

Có một example cách đạt được điều này bằng khoảng thời gian từ tài liệu Góc. Bạn cũng có thể thử nó trong plunker.

Đây là mã:

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> 

Dưới đây là kết quả: enter image description here

46

Chỉ cố gắng cải thiện câu trả lời của Armen. Bạn có thể sử dụng dịch vụ $interval để thiết lập bộ hẹn giờ.

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>

2

Đây là câu trả lời đơn giản nhất tôi có thể đưa ra sử dụng $interval:

Example

Các JS

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

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

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

HTML

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

Đây là một thực hiện hẹn giờ sử dụng chức năng đăng ký $ khoảng cùng đăng ký một khoảng thời gian mới vào đầu, và hủy khoảng trên dừng lại.

CẢNH BÁO!Nó không phải là khả năng liên kết với các tham số $ khoảng chậm trễ

Example

Các 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); 
} 

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

Bạn có thể sử dụng mã này. Nó đơn giản hơn.

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

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

Tôi tạo ra một chỉ thị nhỏ để hiển thị một đồng hồ kỹ thuật số. Chức năng tự gọi là cần thiết vì sẽ có một sự chậm trễ thứ hai khi render đồng hồ.

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>

Các vấn đề liên quan