I'm using angularjs-bootstrap-datetimepicker but I can't figure out how I can make it optional to enter the full date when manually inputing the date instead of using the UI.
That is, I would like to be able to manually enter only "2020" and have it call a function where I can specify if it should be "2020-01-01, 2020-12-31" or something else entirely. While also being able to use the GUI with the intended usage.
I worked around a similar problem with a different datepicker, but the solution may also work here.
I solved my problem by hiding the datepicker's original input and placing a separate input field with ng-model binding to the same scope value. Then I attached an own directive on it which implemented a parser for the user input that understood my custom format. (See ngModel.$parsers):
<input ng-model="my.model" my-parser>
<my-datepicker-directive ng-model="my.model">
The directive was implemented like this. You just need to implement your own myParserFunction()
and myFormattingFunction()
(and myValidationFunction()
if you want to validate the input):
angular.module('app')
.directive('myParser', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModelController) {
/*
* Display -> Model
*/
ngModelController.$parsers.push(function (inputValue) {
if (!myValidationFunction(inputValue)) {
ngModelController.$setValidity('myParser', false);
return null;
}
ngModelController.$setValidity('myParser', true);
return myParserFunction(inputValue);
});
/*
* Model -> Display
*/
ngModelController.$formatters.push(function (modelValue) {
return myFormattingFunction(modelValue);
});
},
};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With