Skip to content
Chris Davies edited this page Oct 12, 2017 · 1 revision

I'm a React guy, but @r3wt shared a snippet to get the date picker playing nice with Angular:

.directive('datePicker',function($parse){

    return {
        restrict: 'A',
        link: function(scope,element,attrs){

            if(attrs.datePickerOptions){
                attrs.$observe('datePickerOptions',function(){
                    link(attrs.datePickerOptions);
                });
            }else{
                link(false);
            }

            function link(options){

                var defaults = {
                    mode: 'dp-below',
                    // Used to convert a date into a string to be used as the value of input. If you specify format,
                    // you must also specify parse. Parse and format are complimentary. Format converts a date to a
                    // string, and parse converts a string to a date.
                    format: function (date) {
                        if(typeof date == 'string'){
                            date = new Date(date);
                        }
                        return date.toLocaleDateString();
                    },

                    // Used to parse a date string and return a date (e.g. parsing the input value)
                    // The value of str can be undefined / null, so you need to handle this case.
                    parse: function (str) {
                        var date = new Date(str);
                        return isNaN(date) ? new Date() : date;
                    }
                };

                var getter = $parse(attrs.ngModel);
                var setter = getter.assign;
                var date = getter(scope);
                setter(scope,defaults.format(date));

                TinyDatePicker( element[0],angular.extend({}, defaults, (options||{})  ));

            }

        }
    };

})
Clone this wiki locally