micanose
9/22/2017 - 9:54 AM

Angular JS minute 2 hour directive and filters

Angular JS minute 2 hour directive and filters

(function () {
	'use strict';

	angular.module('app')
		.directive("timeInput", timeInput);

	timeInput.$inject = ["$timeout"];

	function timeInput($timeout) {
		return {
			restrict: 'E',
			template: '<input type="text" ng-model="display" ng-change="change(\'{{display}}\')" placeholder="{{is === \'h\' ? \'__:__\' : \'\'}}" /><div ng-click="makeCambio()" class="input-time-button">{{is}}</div>',
			scope: {
				ngModel: '=',
				show: '@'
			},
			link: function (scope, elem, attrs) {
				angular.element(elem[0]).addClass("time-input");

				scope.is = "m";
				scope.show = (scope.show || "m");
				scope.cambio = cambio;
				scope.makeCambio = makeCambio;
				scope.display = scope.cambio(scope.ngModel, scope.show);

				scope.change = function (old) {
					var startPos = angular.element(elem[0].firstChild)[0].selectionStart - 1;
					var valid = true;
					if (scope.is === "m") {
						if (!/^[0-9]$/.test(scope.display)) valid = false;
					} else if (scope.is === "h") {
						valid = (!/^([0-9]*):?([0-5])?([0-9])?$/g.test(scope.display)) ? false : valid;
						if ((scope.display.match(/\:/g) || []).length > 0) {
							var parts = scope.display.split(":");
							valid = (parts.length > 2) ? false : valid;
							valid = (parseInt(parts[1]) > 59) ? false : valid;
						}
					}
					console.log(valid)
					if (!valid) {
						scope.display = old;
						$timeout(function () {
							var e = angular.element(elem[0].firstChild)[0];
							if (e.createTextRange) e.createTextRange().move('character', startPos).select();
							else if (e.selectionStart) {
								e.focus();
								e.setSelectionRange(startPos, startPos);
							} else e.focus();
						});
					}
				};

				function makeCambio() {
					scope.display = cambio();
				}

				function cambio(time, to) {
					to = (((to) ? to.toLowerCase() : false) || ((scope.is === "m") ? "h" : "m"));
					time = (time || scope.display);
					var result = time;

					if ((to === "h") && (scope.is !== "h")) {
						var
							h = Math.trunc(time / 60),
							t = time % 60;

						result = ((h < 10) ? "0" + h : h) + ":" + ((t < 10) ? "0" + t : t);
						scope.is = "h";
					} else if ((to === "m") && (scope.is !== "m")) {
						var actual = time.split(":");
						result = (parseInt((actual[0] || 0)) * 60) + parseInt((actual[1] || 0));
						scope.is = "m";
					}

					return result;
				}


			}
		}
	}

})();
(function () {
	'use strict';

	angular.module('app')
		.filter("m2h", m2h)
		.filter("h2m", h2m);

	function m2h() {
		return function (minute) {
			var h = Math.trunc(minute / 60), t = minute % 60;
			return ((h < 10) ? "0" + h : h) + ":" + ((t < 10) ? "0" + t : t);
		}
	}

	function h2m() {
		return function (hours) {
			var actual = hours.split(":");
			return (parseInt((actual[0] || 0)) * 60) + parseInt((actual[1] || 0));
		}
	}

})();