Created
September 19, 2014 14:33
-
-
Save alexandrricov/305a2b71f9b9d0cd0fca to your computer and use it in GitHub Desktop.
seconds (number) to "hh : mm : ss" (string)
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
<!doctype html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Lol</title> | |
<style> | |
.ng-invalid { | |
border-color: red; | |
} | |
</style> | |
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.2/angular.min.js"></script> | |
<script src="script.js"></script> | |
</head> | |
<body ng-app="docsTimeDirective"> | |
<div ng-controller="Controller"> | |
<div>{{ dataHolder.seconds }} seconds</div> | |
<hr> | |
<input type="text" transform-time ng-model="dataHolder.seconds"> | |
</div> | |
</body> | |
</html> |
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
angular.module('docsTimeDirective', []) | |
.controller('Controller', ['$scope', function($scope) { | |
$scope.dataHolder = { | |
seconds: 61 | |
}; | |
}]) | |
.directive('transformTime', function () { | |
'use strict'; | |
return { restrict: 'A', | |
require: 'ngModel', | |
link: function (scope, element, attrs, ngModel) { | |
if (ngModel) { | |
ngModel.$parsers.push(function (value) { | |
var hours, | |
minutes, | |
seconds, | |
a; | |
a = value.split(':'); | |
hours = +a[0]; | |
minutes = +a[1]; | |
seconds = +a[2]; | |
ngModel.$setValidity('hours', hours < 24); | |
ngModel.$setValidity('minutes', minutes < 60); | |
ngModel.$setValidity('seconds', seconds < 60); | |
return hours * 60 * 60 + minutes * 60 + seconds; | |
}); | |
ngModel.$formatters.push(function (value) { | |
var hours, | |
minutes, | |
seconds; | |
hours = parseInt(value / 3600) % 24; | |
if (parseInt(hours) < 10 && hours.toString().length < 2) { | |
hours = '0' + hours; | |
} | |
minutes = parseInt(value / 60) % 60; | |
if (parseInt(minutes) < 10 && minutes.toString().length < 2) { | |
minutes = '0' + minutes; | |
} | |
seconds = value % 60; | |
if (parseInt(seconds) < 10 && seconds.toString().length < 2) { | |
seconds = '0' + seconds; | |
} | |
return hours + ' : ' + minutes + ' : ' + seconds; | |
}); | |
} | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment