首页 文章

将bootstrap datepicker包装为指令

提问于
浏览
0

我试图用一个角度指令包装bootstrap datepicker以及常见的datepicker,这个datepicker包含一个不同的dateformat用于显示和ng-model的不同日期格式 .

并得到一个错误:

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

});

谢谢

2 回答

  • 2

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

  • 0

    顺便问一下你原来的问题是因为

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

相关问题