Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
982 views
in Technique[技术] by (71.8m points)

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

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?

tia Sam

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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');
            });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...