AngularJS Stopwatch
How to master AngularJS Directives. AngularJS Stop Watch
by pertrai1
HTML
<script src="http://code.angularjs.org/1.2.3/angular.js"></script>
<div ng-app="stopWatchApp" ng-controller="stopWatchDemoCtrl">
<div ng-repeat="options in stopwatches">
<div bb-stopwatch options="options">
<div class="container">
<div class="stopWatch numbers">
{{options.elapsedTime | date:'h:mm:s'}}
</div>
<button class="btn" ng-click="startTimer()">Start</button>
<button class="btn" ng-click="stopTimer()">Stop</button>
<button class="btn" ng-click="resetTimer()">Reset</button>
</div>
</div>
<div class="log" ng-repeat="log in options.log">
{{log/1000}} seconds
</div>
</div>
</div>
CSS
.stopWatch {
padding: 5px;
background: linear-gradient(top, #222, #eee);
border: 7px solid #efefef;
border-radius: 5px;
display: inline-block;
margin: 10px auto;
box-shadow:
inset 0 -2px 10px 1px rgba(0, 0, 0, 0.75),
0 5px 20px -10px rgba(0, 0, 0, 1);
}
.numbers {
font-size: 30px;
line-height: 40px;
font-family: digital, arial, verdana;
color: black;
}
@font-face {
font-family: 'digital';
src: url('http://thecodeplayer.com/uploads/fonts/DS-DIGI.TTF');
}
.container {
padding: 5px;
text-align: center;
}
JavaScript
angular.module('stopWatchApp', [])
.controller('stopWatchDemoCtrl', ['$scope', function($scope){
$scope.stopwatches = [{ log: []},{interval: 1000, log: []},{interval: 2000, log: []}];
}])
.directive('bbStopwatch', ['StopwatchFactory', function(StopwatchFactory){
return {
restrict: 'EA',
scope: true,
link: function(scope, elem, attrs){
var stopwatchService = new StopwatchFactory(scope[attrs.options]);
scope.startTimer = stopwatchService.startTimer;
scope.stopTimer = stopwatchService.stopTimer;
scope.resetTimer = stopwatchService.resetTimer;
}
};
}])
.factory('StopwatchFactory', ['$interval', function($interval){
return function(options){
var startTime = 0,
currentTime = null,
offset = 0,
interval = null,
self = this;
if(!options.interval){
options.interval = 100;
}
options.elapsedTime = new Date(0);
self.running = false;
function pushToLog(lap){
if(options.log !== undefined){
options.log.push(lap);
}
}
self.updateTime = function(){
currentTime = new Date().getTime();
var timeElapsed = offset + (currentTime - startTime);
options.elapsedTime.setTime(timeElapsed);
};
self.startTimer = function(){
if(self.running === false){
startTime = new Date().getTime();
interval = $interval(self.updateTime,options.interval);
self.running = true;
}
};
self.stopTimer = function(){
if( self.running === false) {
return;
}
self.updateTime();
offset = offset + currentTime - startTime;
pushToLog(currentTime - startTime);
...