Overview: This code snippet shows how to display the system date and time every second. It also uses the $interval to start and stop a watch with a 1 second interval. The stop watch is started with a button ng-click function call to startTimer. The $interval is assigned to the stopwatch variable and a promise variable is returned. The promise variable is used to stop the timer.
HTML and boostrap code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Clock</title>
<link href="/Content/bootstrap.min.css" rel="stylesheet">
<script src="/Scripts/angular.min.js"></script>
<script src="/Scripts/clockController.js"></script>
</head>
<body>
<div class="container">
<div ng-app="ClockApp">
<div ng-controller="ClockController">
<div class="panel panel-default">
<div class="panel-heading">
<h3>Current Time</h3>
</div>
<div class="panel-body">
<p>{{clock | date:'MMMM dd yyyy EEEE'}}</p>
<p>{{clock | date:'hh:mm:ss a'}}</p>
<h3>Stop Watch</h3>
<p>{{stopWatchDisplay}}</p>
<button id="Start" ng-click="startTimer()">Start</button>
<button id="Stop" ng-click="stopTimer()">Stop</button>
<button id="Reset" ng-click="resetTimer()">Reset</button>
</div>
</div>
</div>
</div>
</div>
<script src="/Scripts/jquery-1.9.1.min.js"></script>
<script src="/Scripts/bootstrap.min.js"></script>
</body>
</html>
Angular JS controller code
var myApp = angular.module('ClockApp', []);
var promise;
myApp.controller('ClockController', function ($scope,$interval) {
$scope.tickInterval = 1000;
var iStopWatchSeconds = 1;
var tick=function(){
$scope.clock = Date.now();
}
tick();
$interval(tick, $scope.tickInterval);
var stopWatch = function () {
$scope.stopWatchDisplay = iStopWatchSeconds;
iStopWatchSeconds++;
}
$scope.startTimer = function () {
promise=$interval(stopWatch, 1000);
}
$scope.stopTimer = function () {
if(angular.isDefined(stopWatch)){
$interval.cancel(promise);
}
}
$scope.resetTimer = function () {
$scope.stopTimer();
iStopWatchSeconds=1
$scope.stopWatchDisplay = '';
}
});