JSFiddle - React, Tailwind, and code Playground

by Minh Nguyen

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<html ng-app="myapp">
<body>
<div>
    <!-- this input is for changing the directive internal value for test purpose-->
    Change here:
    <input type="number" ng-model="timeValue" ng-init="timeValue = 150000"/>
    <br/>
    This need to be consistent:
    <time-input value="timeValue"></time-input>
</div>
</body>
</html>

JavaScript

angular.module('myapp', [])
    .directive('timeInput', function () {
    return {
        restrict: 'E',
        template: '<input type="text" ng-model="ctrl.strValue" ng-blur="ctrl.onChange()"/><span ng-bind="ctrl.value"></span>',
        scope: {
            'value': '='
        },
        controller: Controller,
        controllerAs: 'ctrl',
        bindToController: true
    };

    function Controller() {
        var ctrl = this;
        ctrl.value = ctrl.value || 0;
        ctrl.strValue = "00:00";

        /**
         *	Called when the UI determine user input value has change,
         *	Set the internal value to be same as user input text value.
         **/
        function onChange() {
            var hour = ctrl.strValue.substr(0, 2);
            var minute = ctrl.strValue.substr(3);
            var dateObj = new Date(ctrl.value);
            var regex = new RegExp("^\\d{2}:\\d{2}$");
            // If format is not valid, revert to last value
            if (!ctrl.strValue.match(regex)) {
                ctrl.strValue = ("0"+dateObj.getUTCHours()).slice(-2) + ":" + ("0"+dateObj.getUTCMinutes()).slice(-2);
                return;
            }
            
            dateObj.setUTCHours(hour);
            dateObj.setUTCMinutes(minute);
            ctrl.value = dateObj.getTime();
        }
        ctrl.onChange = onChange;
        
        function filterText() {
        
        }
    }
});