Angular - ui-bootstrap - datepicker - Is there a way of detecting when the month has changed?

后端 未结 4 873
[愿得一人]
[愿得一人] 2020-12-20 21:03

I\'d like to set the date to the 1st of the currently selected month when it\'s changed.

is there a way without monitoring click event on the month\'s buttons?

4条回答
  •  北海茫月
    2020-12-20 21:24

    Datepicker's scope has a property 'activeDateId' that you can watch. It changes when you switch months.

    I think the best way is to create a 'decorator' on the datepicker directive so you can add functionality to it. You can access its scope if you override the directive's 'compile' function.

    You do this in a module.config function:

    $provide.decorator('datepickerDirective', function($delegate) {
        var directive = $delegate[0];
    
        /* Override compile */
        var link = directive.link;
    
        directive.compile = function() {
            return function(scope, element, attrs, ctrl) {
                link.apply(this, arguments);
    
                scope.$watch('activeDateId', function() {
                  console.log('switched');
                });
            }
        };
    
        return $delegate;
    });
    

    EDIT

    I ran into an issue with code similar to this where if you switch the month and the 2 months have their 1st date on the same day, the $watch won't fire. You can get around this by watching the value of the property 'activeDate' in Datepicker's controller:

                scope.$watch(function() {
                  return ctrl.activeDate.getTime();
                }, function() {
                  console.log('switched');
                });
    

提交回复
热议问题