0

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?

Community
  • 1
  • 1
Nico Prediger
  • 43
  • 1
  • 1
  • 7
  • Possibly is the same as http://stackoverflow.com/a/29194068/2435473 – Pankaj Parkar Jun 03 '15 at 10:23
  • @pankajparkar Please note, that the ngmodel already is notified. I want angular to notify the datepicker, not the other way around. Unless I completely misunderstood your answer, scope.apply won't help. – Nico Prediger Jun 03 '15 at 12:34

1 Answers1

1

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.

Nico Prediger
  • 43
  • 1
  • 1
  • 7