如何在 AngularJS 和 HTML 中制作滴答时钟(时间)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23383233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a ticking clock (time) in AngularJS and HTML
提问by rex
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.
我是一个初学者 AngularJS/html 用户,他一直试图找到一个代码片段来为 Web 应用程序制作时钟/时间项。
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!
我已经发布了我的解决方案,但想在选择答案之前看看是否有更好的解决方案!
回答by rustyx
Just trying to improve Armen's answer. You can use the $interval
service to setup a timer.
只是试图改善Armen的答案。您可以使用该$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>
回答by rex
This works quite nicely for me and I think is easy to follow for noobs. See it in action here
这对我来说非常有效,我认为新手很容易理解。在这里看到它的行动
JavaScript:
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:
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.
不要忘记在 body 标签中包含 angularJS 和“ng-app”。
回答by Sma?l Hammour
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>
回答by Wilmer Saint
This is the simplest answer I could come up with using $interval:
这是我可以使用$interval想出的最简单的答案:
The JS
JS
function TimeCtrl($interval) {
var timeController = this;
timeController.clock = { time: "", interval: 1000 };
$interval(function () {
timeController.clock.time = Date.now();},
timeController.clock.interval);
}
The HTML
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.
这是一个定时器实现,使用相同的 $interval 注册函数在开始时注册一个新的间隔,并在停止时取消间隔。
WARNING! It is not possible to bind to the $interval delay parameter
警告!无法绑定到 $interval 延迟参数
The JS
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
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>
回答by Nick
There is an exampleof how to achieve this using interval from the Angular docs. You can also try it out in plunker.
有一个示例说明如何使用 Angular 文档中的间隔来实现这一点。您也可以在 plunker 中尝试一下。
Here is the code:
这是代码:
Javascript:
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
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>
Here is the result:
结果如下:
回答by viparvez
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval) {
$scope.theTime = new Date().toLocaleTimeString();
$interval(function () {
$scope.theTime = new Date().toLocaleTimeString();
}, 1000);
});
回答by Marquise Mery
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>
回答by kurtzmarc
The best way to do this is to use an Observable interval:
最好的方法是使用 Observable 间隔:
this.now = interval(1000).pipe(timestamp(), map(t => new Date(t.timestamp)));
Then use the async and date pipes to display the data:
然后使用 async 和 date 管道来显示数据:
Now: {{ this.now | async | date: 'mediumTime' }}