AngularJS stopwatch service
by marolt93
HTML
<h1>{{myStopwatch.data.value}}</h1>
<h3>{{myStopwatch.data.laps|json}}</h3>
<button ng-click='myStopwatch.start()'>Start</button>
<button ng-click='myStopwatch.stop()'>Stop</button>
<button ng-click='myStopwatch.reset()'>Reset</button>
<button ng-click='myStopwatch.lap()'>Lap</button>
JavaScript
function Main($scope, stopwatch) {
$scope.myStopwatch = stopwatch;
}
angular
.module('stopwatch', [])
.constant('SW_DELAI', 100)
.factory('stopwatch', function (SW_DELAI,$timeout) {
var data = {
value: 0,
laps: []
},
stopwatch = null;
var start = function () {;
stopwatch = $timeout(function() {
data.value++;
start();
}, SW_DELAI);
};
var stop = function () {
$timeout.cancel(stopwatch);
stopwatch = null;
};
var reset = function () {
stop()
data.value = 0;
data.laps = [];
};
var lap = function () {
data.laps.push(data.value);
};
return {
data: data,
start: start,
stop: stop,
reset: reset,
lap: lap
};
});