我试图用一个angular指令包装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);
}
};
});
由于
答案 0 :(得分:2)
为什么重新发明轮子?使用ui-bootstrap
指令datepicker
- http://angular-ui.github.io/bootstrap/#/datepicker
答案 1 :(得分: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;
});
}