1
votes

I have a simple directive called po-datepicker, it displays a datepicker on the screen, but allows the user to type a date manually:

<input type="text" ng-model="model" po-datepicker required />

and this is the directive:

myApp.directive('poDatepicker', function () {
    return {
        require: ['?^ngModel'],
        restrict: 'A',
        link: function ($scope, elem, attrs, ctrl) {
            var ngModel = ctrl[0];
            var picker = elem.datepicker();

            picker.on('changeDate', function(e) {
                ngModel.$setViewValue(e.date);
                ...
            });

            elem.parent().find('button').on('click', function() {
                picker.datepicker('show');
            });

            var changeFn = function(e) {
                // Here I have some logic that calls $setViewValue();
            };

            picker.on('hide', changeFn);
            elem.on('keyup blur', changeFn);
        }
    };
});

this works as expected, but when I try to type a value in the input, it updates the ngModel, changing the variable in the scope, how can I prevent ngModel from being changed in the input?

Here is a plunkr, try manually writing a value and you'll understand what I'm talking.

2
Why don't you associate the text input with a different model object. Then at the appropriate time, you can commit the value to the real model object.Sunil D.
If I do that, the validations such as required will not work, since it needs ngModel to validateEvandro Silva

2 Answers

1
votes

Actually, after some research, I found a solution for this problem.

What I found on forums and questions is that I needed to unbind the element's events, like this:

elem.unbind('input').unbind('keydown').unbind('change');

But that solution didn't work as expected.

The problem is that I'm currently using Angular 1.2.x, I found out that you need also to set some priority to the directive, such as:

return {
    require: ['?^ngModel'],
    priority: 1,
    ...
}

The priority: 1 is needed in this case, because of the priority of some internal Angular.js directives.

Here is an updated plunker with the right priority set up.

0
votes

Just add 'disabled' to the input http://plnkr.co/edit/xFeAmSCtKdNSQR1zbAsd?p=preview

 <input type="text" class="form-control" ng-model="test" po-datepicker required feedback disabled/>