4

I need to make a call to my backend, when user change month on datepicker calendar is that possible with UI Bootstrap 1.3 ?

jack wolier
  • 330
  • 1
  • 4
  • 11

1 Answers1

5

You can extend the datepicker directive using a decorator, and in the decorator overwrite the compile function to add a $watch on activeDate. You can check if the month or year of the date has changed, and if so call a function on a service that you inject into the decorator. Pass in the date if necessary and in the service perform your call to the backend.

Example below and in fiddle - MyService is just logging the date but you can replace with call to backend.

var app = angular.module('app', ['ui.bootstrap']);

angular.module('app').service('MyService', function() {
    this.doStuff = function(date) {
        console.log(date);
    }
});

angular.module('app').config(function($provide) {
    $provide.decorator('datepickerDirective', ['$delegate', 'MyService', function($delegate, MyService) {
        var directive = $delegate[0];

        var link = directive.link;

        directive.compile = function() {
            return function(scope, element, attrs, ctrls) {
                link.apply(this, arguments);

                scope.$watch(function() {
                    return ctrls[0].activeDate;
                }, function(newValue, oldValue) {
                    if (oldValue.getMonth() !== newValue.getMonth() 
                       || oldValue.getYear() !== newValue.getYear()) {
                        MyService.doStuff(newValue);
                    }
                }, true);
            }
        };
        return $delegate;
    }]);
});
sp00m
  • 47,968
  • 31
  • 142
  • 252
sheilak
  • 5,833
  • 7
  • 34
  • 43
  • I need to make a call to the server to get an array of hoildays for the current year and use that array to disable the days in the datepicker, I tried to achieve using your code as I am new to angularjs decorator, but `$scope.disabled()` function in my controller executes before the `$watch` function, if I could override the date-disabled directive of the datepicker or override `$scope.disabled()` function then maybe I can achieve it but don't exactly know how, could you help – sreekanthk Oct 13 '15 at 07:20
  • You can call ctrls[0].refreshView() to update the datepicker after the server call completes – sheilak Oct 14 '15 at 09:54
  • I'm getting "Unknown provider: datepickerDirectiveProvider" error, any ideas why? – tomek550 Oct 24 '16 at 08:31
  • 1
    What version of UI Bootstrap are you on? In the recent versions the directive is called 'uibDatepicker' rather than 'datepicker' – sheilak Oct 24 '16 at 09:01
  • 1
    Thank you, that works :) I've tried it before, but looks like I've misspelled :) – tomek550 Oct 24 '16 at 12:04