将引导日期选取器包装为指令



我正在尝试用角度指令包装引导日期选择器除了通用日期选择器之外,此日期选择器还包含用于显示的不同日期格式和用于 NG 模型的不同日期格式。

并收到错误:

 Error: [$rootScope:inprog] $digest already in progress

我的代码粘贴在下面:

app.directive('ngDatePicker', function () {
return {//this datePicker will show the date in the wanted format and save it (ng-model) with the default format of yy-mm-dd
    template: "<span><input id='displayDate' class={{class}} type='text'/><input id='hiddenDate' type='text' style='display:none'/></span>",
    require: 'ngModel',
    replace: true,
    scope: {
        ngModel: '=',
        class: '@'
    },
    link: function (scope, element, attrs, ngModelCtrl) {
        // set date pickers - this datePicker 
        var displayInput = element.find('#displayDate');
        var hiddenInput = element.find('#hiddenDate');
        var options = {};
        options.minDate = new Date();
        options.format = "yyyy-MM-dd";
        options.autoclose = 'true';
        displayInput.datepicker(options);
        displayInput.datepicker().on('changeDate', function () {
            //update the ng-model 
            var changedDate = displayInput.datepicker("getDate");
            var newDate = converDateToDefault(changedDate);
            if (scope.ngModel != newDate) {
                scope.$apply(function () {
                    hiddenInput.val = newDate;
                    scope.ngModel = newDate;
                });
            }
        });
        scope.$watch("ngModel", function (newVal) {
            if (typeof newVal !== undefined && newVal != null && newVal != "") {
                displayInput.datepicker('destroy');
                var option = {};
                option.format = "yyyy-MM-dd";
                displayInput.datepicker(option);
                var convertedVal = converDateToDefault(displayInput.datepicker("getDate"));
                if (convertedVal != "Invalid date" && newVal != convertedVal) {
                    displayInput.datepicker("setDate", convertDate(newVal));
                    hiddenInput.val = newVal;
                }
            }
        }, true);
    }
};

});

谢谢

为什么要重新发明轮子?使用ui-bootstrap指令datepicker - http://angular-ui.github.io/bootstrap/#/datepicker

>顺便说一句,你原来的问题是因为

       scope.$apply(function () {
                hiddenInput.val = newDate;
                scope.ngModel = newDate;
            });

您可以通过包装范围来解决它$apply

 if (scope.$root.$$phase != '$apply' && scope.$root.$$phase != '$digest') {
       scope.$apply(function () {
                hiddenInput.val = newDate;
                scope.ngModel = newDate;
            });
  }

最新更新