willem
willem

Reputation: 27027

In angularJS, why is my model not updating when linking the input to a datepicker?

I'm a little lost here. I defined an angular directive that creates a datepicker (the bootstrap datepicker by eternicode(https://github.com/eternicode/bootstrap-datepicker/)):

The datepicker appears to work visually. It pops up, and puts a value in my textbox. But the angular model is not updated unless I edit the textbox by hand.

My directive:

myApp.directive('ccDatePicker', function ($compile) {
    return {
        restrict: 'EA',
        template: '<input type="text" ng-model="ngModel" />',
        require: '^ngModel',
        scope: {
            ngModel: '='
        },
        replace: false  ,
        link: function (scope, element, attrs) {
            element.children(0)
                .on('change', function () { scope.$digest(); })
                .datepicker({ format: 'yyyy/mm/dd', autoclose: true });
        }
    };
});

My HTML:

<label>Due date: <cc-date-picker ng-model="todoObject.dueBy" /></label>

<div>
    dueBy: {{todoObject.dueBy}} (updates when editing textbox by hand, but not when using date picker)
</div>

I used scope.$digest to refresh the model, and I also tried scope.$apply. No luck.

How do I get my angular model to update when the user chooses a date in the date picker?

Upvotes: 2

Views: 1641

Answers (2)

user1220617
user1220617

Reputation: 11

if you set the dueBy date first (eg.

$scope.todoObject={dueBy:"04/27/2015"};

how to make the dropdown show the initial value when it's first displayed?

http://plnkr.co/edit/xOzfQOOMe1GFoB1tfQiF?p=preview

Upvotes: -2

ms87
ms87

Reputation: 17492

I had a similar problem when trying to make a datepicker directive based on a jQuery plugin, because the datepikcer's onSelect() event happens outside the angular world and no notifications are raised, you need to call a $scope.$apply() force a digest to let angular know that it should update the model value:

onSelect: function (date) {
   scope.$apply(function () {
      ngModelCtrl.$setViewValue(date);
   });
}

Also in the snippet you posted, I don't see where you're setting the models value, hence this line:

ngModelCtrl.$setViewValue(date);

EDIT

I made a plunk demonstrating what needs to be done. On an unrelated note, why don't you use the angular-ui datepicker?

Upvotes: 1

Related Questions