Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defaulting to start or end of year if only year is entered in angularjs-bootstrap-datepicker

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.

like image 613
Oskar Persson Avatar asked Jan 24 '20 14:01

Oskar Persson


1 Answers

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);
        });
      },
    };
  });
like image 101
hoeni Avatar answered Oct 20 '22 21:10

hoeni