Last active
August 29, 2015 14:07
-
-
Save jwoertink/5256e80f393a150f8b21 to your computer and use it in GitHub Desktop.
A small timer directive for AngularJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# assumes there's already a window.timer = {} | |
app.directive 'callTimer', -> | |
opts = | |
restrict: 'E' | |
controller: ($scope, $rootScope)-> | |
$scope.minutes = (window.timer?.state.minutes || 0) | |
$scope.seconds = (window.timer?.state.seconds || 0) | |
$scope.$on 'start-timer', -> $scope.startTimer() | |
$scope.$on 'stop-timer', -> $scope.stopTimer() | |
$scope.startTimer = -> | |
incrementTimer = -> | |
$scope.seconds += 1 | |
if $scope.seconds >= 60 | |
$scope.seconds = 0 | |
$scope.minutes += 1 | |
window.timer.state = | |
minutes: $scope.minutes | |
seconds: $scope.seconds | |
$rootScope.setTimeDisplay($scope.minutes, $scope.seconds) | |
$rootScope.$digest() | |
window.timer = | |
interval: window.setInterval(incrementTimer, 1000) | |
state: | |
minutes: $scope.minutes | |
seconds: $scope.seconds | |
$scope.stopTimer = -> | |
$scope.$emit('timer-stopped', window.timer.state) | |
$scope.minutes = 0 | |
$scope.seconds = 0 | |
window.clearInterval(window.timer.interval) | |
$rootScope.setTimeDisplay($scope.minutes, $scope.seconds) | |
window.timer = null | |
$rootScope.setTimeDisplay = (m, s)-> | |
$scope.minDisplay = String(m).padLeft('0', 2) | |
$scope.secDisplay = String(s).padLeft('0', 2) | |
$rootScope.setTimeDisplay($scope.minutes, $scope.seconds) | |
# use with <call-timer>{{minDisplay}}:{{secDisplay}}</call-timer> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment