Last Updated: September 04, 2017
·
11.09K
· kjana83

jQuery Datepicker with AngularJs

This directive helps to use the jQuery datepicker with angualrJs. In addition(optionally) I need to compare with some date. (if the date is not given comparing with todays date.

app.directive('ngDate', function() {
    return {
        restrict: 'A',
        require : 'ngModel',
        link : function (scope, element, attrs, ctrl) {
                element.datepicker({
                changeYear:true,
            changeMonth:true,
                    dateFormat:'dd/M/yy',
                    onSelect:function (date) {
                        ctrl.$setViewValue(date);
            if (attrs.hasOwnAttribute('futureDate'))
            {
                var dateToCompare=scope.$eval(attrs.futureDate);
                if (!dateToCompare) dateToCompare=new Date();
                (date>dateToCompare)?ctrl.$setValidity('future',true):ctrl.$setValidity('future',false);
            }
                        scope.$apply();
                    }
                });
        }
    }; 
});

<input type='text' data-ng-model='some.DateField' data-ng-date='' data-futurDate='some.DateToCompare' name='dateControl' readonly='readonly'> 

<div class='error' data-ng-show='testForm.dateControl.$error.future'>
Date cannot be greater than some date.
</div>

3 Responses
Add your response

undefined is not a function error is thrown at attrs.hasOwnAttribute

over 1 year ago ·

Thank you! Very helpful :)

over 1 year ago ·

After fixing these two issues this directive worked for me.
1. Uncaught TypeError: attrs.hasOwnAttribute is not a function
Instead use attrs.hasOwnProperty
2. attrs.futureDate is undefined
Instead use attrs.futuredate

over 1 year ago ·