AngularJS Timer
this is a small fiddle with a quite special timer
HTML
<div ng-app="MyApp" ng-controller="TimerCtrl">
<form>
<button ng-click="startTimer()" ng-disabled="timerRunning">Start</button>
<button ng-click="stopTimer()">Stop</button>
</form>
<div class="timer" ng-style="fontSize">
<h1><timer interval="1000" autostart="true" startTime="09/05/2018 12:20:00"/>{{hhours}}:{{mminutes}}:{{sseconds}}</h1>
</div>
</div>
JavaScript
angular.module('MyApp', ['timer'])
.controller('TimerCtrl', ['$scope', function ($scope) {
$scope.timerRunning = false;
$scope.startTimer = function () {
$scope.$broadcast('timer-start');
$scope.timerRunning = true;
};
$scope.stopTimer = function () {
$scope.$broadcast('timer-stop');
$scope.timerRunning = false;
};
}]);
var timerModule = angular.module('timer', [])
.directive('timer', ['$compile', function ($compile) {
return {
restrict: 'EA',
replace: false,
scope: {
interval: '=',
autoStart: '&',
startTime: "="
},
controller: ['$scope', '$element', '$attrs', '$timeout', function ($scope, $element, $attrs, $timeout) {
$scope.millis = 0;
$scope.autoStart = $attrs.autoStart || $attrs.autostart;
$element.append($compile($element.contents())($scope));
alert($attrs.startTime);
$scope.startTime = new Date($attrs.startTime);
$scope.endTime = null;
$scope.timeoutId = null;
$scope.isRunning = false;
$scope.$on('timer-start', function () {
$scope.start();
});
$scope.$on('timer-stop', function () {
$scope.stop();
});
$scope.$on('timer-clear', function () {
$scope.clear();
});
function resetTimeout() {
if ($scope.timeoutId) {
clearTimeout($scope.timeoutId);
}
}
$scope.start = function () {
$scope.startTime = new Date($scope.startTime);
resetTimeout();
tick();
$scope.isRunning = true;
};
$scope.stop = function () {
var timeoutId = $scope.timeoutId;
$scope.clear();
...