Hour and Minute Angular Directive
I needed to create directive for hour and minute input. There is input type="time"
, but my supervisor didn’t like to have default colon and dash and whatever. So I was asked to create directive for hour and minute input.
Let’s list up the directive specifications:
- No space, no alphabets. Those are not allowed to enter.
- Help users enter. Like insert colon after hour. Correct inappropriate value… etc
- Show errors when the input value is not in correct format.
Anyway, let’s look the codepen first!
See the Pen hour minute input directive3 by Kohei Arai (@1kohei1) on CodePen.
If you want to read the entire html and javascript in nice color syntax, here is the Github gist
Let me go through each line of code for my future reference.
Remove all space, alphabetical characters. Set up the variable for hour and minute. If the passed value has colon in that, set the minute to the second index of num splitted by “:”. cursorPos
is used to set the cursor after the value is renderred.
Those variables are to track what users have done to input. When the length of num is zero, that means all the value is deleted, so empty input.
This part takes care of when the colon is deleted. When minute is only one digit, delete the minute instead of colon. When minute exists, leave the input value unchanged and set the cursor after colon.
This snippet handles all the other case: typed, replaced, and deleted. If hour is over 12, that means it is out of the range. So set the hour to 12 and move to the cursor after colon. If hour is greater than 10 and less than equal to 12, add “:”. For this case, there are two cases. 1. User is editing an hour 2. User is editing minute and hour is in that range. If the cursorPos
is in hour range, that is 1. So move the cursor after the colon.
The same thing for minute too. If the minute is greater than 59, set it to 59. Other than that, if the minute is one number, put zero after that. !isTimeAlreadySet
is for the case the ng-model value is set at the first call. Without this, the minute behaves strange way when ng-model has the initial value.
Set the preValue
, change the input view, and set the cursor at appropriate position.
This link was helpful to pass the variable from view to directive. If there is anything unclear, play with codepen or Github gist. Thank you!