AngularJS: Minute Format Directive
by Erin
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div ng-controller="mainCtrl">
<label for="num" class="lbl">Enter total minutes to format:</label>
<input type="number" id="num" name="num" ng-model="manualMins" min="0" placeholder="Enter total minutes to format" ng-change="updateValue(manualMins)" class="manual_input" />
<format-mins total-mins="duration"></format-mins>
</div>
CSS
div {
text-align: center;
}
.time_wrapper {
display: inline-block;
margin: 10px;
}
.time_wrapper:last-child {
padding-left: 20px;
}
.lbl {
font-family: Arial, Helvetica, sans-serif;
color: #405058;
text-shadow: 1px 1px 0 #fff;
}
input[type='number'].manual_input {
font-family: "Arial Black", Gadget, sans-serif;
color: #405058;
text-shadow: 1px 1px 0 #fff;
padding: 10px;
border: none;
border-bottom: solid 2px #b8b8b8;
transition: border 0.1s;
font-size: 25px;
width: 150px;
margin: 20px auto;
display: block;
text-align: center;
background-color: #f9f9f9;
}
input[type='number'].manual_input:focus,
input[type='number'].manual_input.focus {
border-bottom: solid 6px #969696;
}
.sm_text,
.lg_text {
font-family: "Arial Black", Gadget, sans-serif;
text-align: center;
display: block;
line-height: 1;
color: #405058;
text-shadow: 1px 1px 0 #fff;
}
.lg_text {
font-size: 50px;
}
.sm_text {
font-size: 16px;
}
JavaScript
var app = angular.module('fiddleApp', []);
app.controller('mainCtrl', ['$scope', function ($scope) {
$scope.manualMins = 59;
$scope.duration = {
amount: $scope.manualMins
};
$scope.updateValue = function (newValue) {
$scope.duration = {
amount: newValue
};
};
}]);
app.directive('formatMins', function () {
return {
restrict: 'E',
template: '<div ng-repeat="item in formattedTime" class="time_wrapper">'
+ '<span class="lg_text">'
+ '{{ item.result }}'
+ '<span class="sm_text">'
+ '{{ item.value }}'
+ '</span>'
+ '</span>'
+ '</div>',
replace: true,
scope: {
totalMins: '='
},
link: function (scope,elem,attrs) {
scope.calculateTime = function (duration) {
var time, text;
if (duration < 60) {
time = duration;
if (time == 1) {
text = 'minute';
} else {
text = 'minutes';
}
scope.formattedTime = [{
result: time,
value: text
}];
} else if (duration % 60 == 0) {
time = (duration - duration % 60) / 60;
if (time > 1) {
text = 'hours';
} else {
text = 'hour';
}
scope.formattedTime = [
{
result: time,
value: text
},
{
result: 0,
value: 'minutes'
}
];
} else {
var time1 = (duration - duration % 60) / 60,
time2 = duration % 60,
text2 = 'minutes';
...