Reputation: 2727
I am trying to wrap the bootstrap datepicker with an angular directive in addition to the common datepicker this datepicker contains a different dateformat for display and different date format for the ng-model.
and getting an error of :
Error: [$rootScope:inprog] $digest already in progress
my code is pasted below:
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);
}
};
});
Thanks
Upvotes: 0
Views: 765
Reputation: 18065
btw your original problem is because of
scope.$apply(function () {
hiddenInput.val = newDate;
scope.ngModel = newDate;
});
you can solve it by wrapping the scope.$apply
if (scope.$root.$$phase != '$apply' && scope.$root.$$phase != '$digest') {
scope.$apply(function () {
hiddenInput.val = newDate;
scope.ngModel = newDate;
});
}
Upvotes: 0
Reputation: 31
Why reinvent the wheel? Use ui-bootstrap
directive datepicker
- http://angular-ui.github.io/bootstrap/#/datepicker
Upvotes: 2