AngularJS Timer
this is a small fiddle with a quite special timer
HTML
<div ng-app="MyApp" ng-controller="TimerCtrl">
<form>
<input type="text" placeholder="Minutes of the speak" ng-model="deadline"></input>
<button ng-click="startTimer(deadline)" ng-disabled="timerRunning">Start</button>
<button ng-click="stopTimer()" ng-disabled="!timerRunning">Stop</button>
</form>
<div class="timer">
<h1 ng-class="timerColor.color"><timer interval="1000" autostart="false"/>{{hhours}}:{{mminutes}}:{{sseconds}}</h1>
</div>
</div>
CSS
.timer {
width: 50%;
margin: 0 auto;
font-size: 20px;
font-family: Calibri;
}
.end {
color:red;
}
JavaScript
var myApp = angular.module('MyApp', ['timer']);
myApp.controller('TimerCtrl', ['$scope', function ($scope) {
$scope.timerColor = {};
$scope.timerRunning = false;
$scope.deadlineInMilli = 0;
$scope.turnRed = function () {
$scope.timerColor.color = 'end';
};
$scope.startTimer = function (deadline) {
$scope.$broadcast('timer-start');
$scope.timerRunning = true;
$scope.deadlineInMilli = +deadline * 1000 * 60;
};
$scope.$on('timer-tick', function (event, data) {
if ($scope.timerRun ning === true && data.millis >= $scope.deadlineInMilli) {
$scope.$apply($scope.turnRed);
}
});
$scope.stopTimer = function () {
$scope.$broadcast('timer-stop');
$scope.timerRunning = false;
};
}]);
var timerModule = angular.module('timer', [])
.directive('timer', ['$compile', function ($compile) {
return {
restrict: 'EAC',
replace: false,
scope: {
interval: '=interval',
startTimeAttr: '=startTime',
endTimeAttr: '=endTime',
countdownattr: '=countdown',
finishCallback: '&finishCallback',
autoStart: '&autoStart',
maxTimeUnit: '='
},
controller: ['$scope', '$element', '$attrs', '$timeout', function ($scope, $element, $attrs, $timeout) {
// Checking for trim function since IE8 doesn't have it
// If not a function, create tirm with RegEx to mimic native trim
if (typeof String.prototype.trim !== 'function') {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
//angular 1.2 doesn't support attributes ending in "-start", so we're
//supporting both "autostart" and "auto-start" as a solution for
//backward and forward compatibility.
$scope.autoStart = $attrs.autoStart || $attrs.autostart;
if ($element.html().trim().length === 0) {
...