Angular Bootstrap Datepicker更改月份事件

jac*_*ier 4 datepicker angularjs angular-ui-bootstrap

当用户使用UI Bootstrap 1.3在datepicker日历上更改月份时,我需要致电后端。

she*_*lak 5

您可以使用装饰器扩展datepicker指令,并在装饰器中覆盖此compile函数以添加$watchon activeDate。您可以检查日期的月份或年份是否已更改,如果已更改,请在注入到装饰器中的服务上调用函数。如果需要,请传递日期,并在服务中执行对后端的呼叫。

下面以及例如小提琴 - MyService只是记录的日期,但你可以调用后端更换。

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;
    }]);
});
Run Code Online (Sandbox Code Playgroud)