Nico Prediger
Nico Prediger

Reputation: 43

Unintended Reset of Bootstrap Datepicker when using angularjs

I'm trying to use Bootstrap Datepicker from eternicode in combination with angularjs.

see jsfiddle

var app=angular.module('myApp', [])
.controller('dateCtrl', function($scope) {
    // Case 1:
    $scope.datepick = '';
    // Case 2:
    //$scope.datepick = '25.04.1986';

    $scope.setFirstDate = function() {
        $scope.datepick= '13.10.1960';
    };

    $scope.setAnotherDate = function() {
        $scope.datepick = '20.02.1967';
    };

});

$(document).ready(function(){
    $('.datepicker').datepicker({
        autoclose: true,
        format: 'dd.mm.yyyy',
        clearBtn: true,
        todayBtn: 'linked',
        todayHighlight: true,
        weekStart: '1',
        calendarWeeks: true,
        keyboardNavigation: false
    });
});

Essentially, it works fine. But when I change the date programmatically, BS Datepicker ignores it. This shows, when you initially load the fiddle and follow these steps:

1) Click on 'First me!'

2) Select the input field, without touching the datepicker

3) Tab out, press Esc, or click anywhere but the datepicker (close it without selecting a date)

You'll see, that the input field is now empty.

This does not happen because of an invalid date-format as suggested in this question: Uncomment line 6 in the fiddle and test case 2. Repeat above steps. The datefield now shows '25.04.1986'.

Also, in both cases you can test clicking the datepicker and then repeating steps 1-3. The input field will show the last date selected by the BS Datepicker.

{{datepick}}

shows, that the ng-model is always accurate, so this question is not a duplicate of this or this question. Seeing that angularjs is always aware of the actual date, I don't see how scope.apply would solve my problem.

This tells me: BS Datepicker is keeping track of his own and will only remember the initial date or the dates selected by the datepicker itself. And when closing without picking a new one, it will reset the input field to this remembered value.

So how can I prevent this from happening?

Upvotes: 0

Views: 2274

Answers (1)

Nico Prediger
Nico Prediger

Reputation: 43

So, I found a workaround for this problem. To keep the Datepicker from resetting the input value, add:

forceParse: false

to your Datepicker options. See updated jsfiddle.

Even though this solves the problem at hand, keep in mind, that the Datepicker will no longer parse/check/correct any inputs.

I do believe this to be a bug and will create an issue at Github.

Upvotes: 1

Related Questions