hour minute input directive3

In this example below you will see how to do a hour minute input directive3 with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by 1kohei1, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright 1kohei1 ©

Technologies

  • HTML
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>hour minute input directive3</title>
  
  
  <link rel='stylesheet prefetch' href='https://rawgit.com/angular/bower-material/master/angular-material.min.css'>

  
  
</head>

<body>

  <div ng-controller="AppCtrl as ctrl" ng-app="MyApp">
  <div layout="row">
    <form name="sampleForm">
      <md-input-container md-no-float>
        <input ng-model="ctrl.timeInput" time-input="ctrl.timeInput" ng-trim="false" placeholder="HH:mm" name="timeInput" validation="sampleForm.timeInput.$error"/>
        <div ng-messages="sampleForm.timeInput.$error">
          <div ng-message="wrongFormat">Start time is not in correct format</div>
          <div ng-message="noAmpm">Please set AM/PM</div>
        </div>
      </md-input-container>
    </form>
    <md-select data-ng-model="ctrl.ampm" placeholder="AM/PM">
      <md-option ng-repeat="ampm in ['AM', 'PM']" ng-value="ampm">{{ ampm }}</md-option>
    </md-select>
  </div>
  {{ ctrl.timeInput }} {{ ctrl.ampm }}  
</div>
  <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-animate.min.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-route.min.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-aria.min.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-messages.min.js'></script>
<script src='https://cdn.rawgit.com/angular/bower-material/v0.10.0/angular-material.js'></script>
<script src='https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-114/assets-cache.js'></script>

  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/1kohei1/hour-minute-input-directive3-ZGqqgq */
(function () {
  'use strict';
  var app = angular.module('MyApp');
  app.controller('AppCtrl', function() {
    var _this = this;
    
    _this.timeInput = "";
    _this.ampm = '';
  });
  app.directive('timeInput', function() {
    return {
      restrict: 'A',
      require: 'ngModel',
      scope: {
        timeInput: '=',
        validation: '='
      },
    link: function(scope, element, attrs, controller) {
        var preValue = '';
        var timeRegex = /(1[012]|[1-9]|0[1-9]):[0-5][0-9]/;

        scope.$watch('timeInput', function(val) {
          scope.validation = {};
          if (val && !timeRegex.test(val)) {
            scope.validation.wrongFormat = 'The time is not in correct format.'
          }
        });
        
        element.bind('input', function(event) {
          ensureHourMinute(element.val());
        });
        
        function ensureHourMinute(value) {
          var nospace = value.replace(/ /g, '');
          var num = nospace.replace(/[^0-9:]/, '');
          
          var hour = num.split(':')[0].slice(0, 2);
          var minute = '';
          if (num.indexOf(':') >= 0) {
            minute = num.split(':')[1].slice(0, 2);
          }
          var cursorPos = element[0].selectionStart;
          
          var isTyped = preValue.length < value.length;
          var isReplaced = preValue.length === value.length;
          var isTimeAlreadySet = num.length - preValue.length > 1;
          
          // Deleted all or Select and replace
          if (num.length == 0 || preValue.length - num.length > 2) {
            return setUpView(hour, minute, cursorPos);
          }
          
          // Colon is deleted
          if (preValue.indexOf(':') >= 0 && num.indexOf(':') === -1) {
            hour = preValue.split(':')[0].slice(0, 2);
            minute = preValue.split(':')[1].slice(0, 2);
            // When minute is already entered, put colon.
            if (minute.length === 1) {
              minute = '';
              hour += ':';
              cursorPos++;
            } else if (minute.length === 2) {
              hour += ':';
              cursorPos++;
            }
            return setUpView(hour, minute, cursorPos);
          }
          
          // Other case
          if (parseInt(hour) > 12) {
            hour = '12:';
            cursorPos = 3;
          } else if (parseInt(hour) >= 10) {
            hour += ':';
            if (cursorPos === 1 || cursorPos === 2) {
              cursorPos = 3;
            }
          } else if (parseInt(hour) >= 0 && num.indexOf(':') >= 0) {
            hour += ':';
          } else if (minute !== '') {
            hour += ':';
          }
          
          if (minute > 59) {
            minute = '59';
          } else if (minute.length === 1 && parseInt(minute) < 10 && (isTyped || isReplaced) && !isTimeAlreadySet) {
            minute += '0';
          }
          
          setUpView(hour, minute, cursorPos);
        }
        
        function setUpView(hour, minute, cursorPos) {
          preValue = hour + minute;
          
          controller.$setViewValue(preValue);
          controller.$render();
          element[0].setSelectionRange(cursorPos, cursorPos);
          
          return preValue;
        }
      }
    }
  });
})();

Comments