How to make a ticking clock (time) in AngularJS and HTML
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>
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.