Saturday, August 13, 2016

AngularJS - Bootstrap Datepicker Model Formatter

I have case to show datepicker for textbox, we can simply bind DateString field to textbox and update. But if we use BootStrap uibDatePicker then it requires to format as Date object before binding to ngModel.

So to resolve this issue, i have created directive to format ngModel value before binding and also parse back to string before updating to controller.

To check how to create BootStrap datepicker check here http://angular-ui.github.io/bootstrap/versioned-docs/1.3.3/#/datepickerPopup 

Just create Directive as follows

    app.directive('datePickerModelFormatter', function () {
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function (scope, element, attr, ngModel) {
                function dateToString(dateValue) {
                    if (dateValue != null) {
                        var dateTimeToReturn = new Date(dateValue);
                        return dateTimeToReturn.toISOString();
                    }
                    return dateValue;
                }

                function stringToDate(stringValue) {
                    if (stringValue != null) {
                        var newOffsetDateTime = new Date(stringValue);
                        return new Date(newOffsetDateTime.setMinutes(newOffsetDateTime.getMinutes() + newOffsetDateTime.getTimezoneOffset()));
                    }
                    return stringValue;
                }

                ngModel.$parsers.push(dateToString);
                ngModel.$formatters.push(stringToDate);
            }
        };

    });



and on HTML just include this model

  <p class="input-group">
          <input type="text" class="form-control" uib-datepicker-popup="{{format}}" ng-model="dt" is-open="popup1.opened" datepicker-options="dateOptions" ng-required="true" close-text="Close" alt-input-formats="altInputFormats" date-picker-model-formatter />
          <span class="input-group-btn">
            <button type="button" class="btn btn-default" ng-click="open1()"><i class="glyphicon glyphicon-calendar"></i></button>
          </span>
        </p>


Thats it, it will convert to DateObject and Return back as StringObject (ISOString format)