Oskar Persson
Oskar Persson

Reputation: 6765

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.

Upvotes: 6

Views: 174

Answers (2)

hoeni
hoeni

Reputation: 3290

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);
        });
      },
    };
  });

Upvotes: 5

Pratik Patel
Pratik Patel

Reputation: 6978

I think you can use minDate and Maxdate

http://next.plnkr.co/edit/VyWzqYk426is0F1g

First click on min date so that it unbales the dated in date picker the input 2020 and hit enter then you can see it disables the dates.

Upvotes: 0

Related Questions