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 ?

1 Answer 1

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;
    }]);
});
Sign up to request clarification or add additional context in comments.

5 Comments

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
You can call ctrls[0].refreshView() to update the datepicker after the server call completes
I'm getting "Unknown provider: datepickerDirectiveProvider" error, any ideas why?
What version of UI Bootstrap are you on? In the recent versions the directive is called 'uibDatepicker' rather than 'datepicker'
Thank you, that works :) I've tried it before, but looks like I've misspelled :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.