I'm using JQuery UI's Datepicker on Date From and Date To fields in an AngularJS project. I've added the directive to bind the value to the model value, and I've also added a check to OnSelect that sets the minDate and maxDate options for each field (so the Date To is never earlier than the Date From). The problem is that, on loading the page, no date has actually been selected (even though the model has a value), so it is still possible to select a To date earlier than the Date From. I added a $watch service to at least correct the error, but I still can't figure out how to set the minDate on load either within the directive or inside the controller. I've also tried $(document).ready outside of the Angular code, but that isn't working either. Here's my code prior to adding anything to set the minDate.
Within controller:
$scope.messagesForm.dateFrom = moment().subtract('days', 30).format('MM/DD/YYYY');
$scope.messagesForm.dateTo = moment().format('MM/DD/YYYY');
$scope.$watch('messagesForm.dateTo', function(newVal, oldVal) {
if (!newVal) return;
if (Date.parse(newVal) < Date.parse($scope.messagesForm.dateFrom)) {
$scope.messagesForm.dateFrom = newVal;
}
});
Directive:
.directive('datepicker', function() {
return {
restrict: 'A',
require : 'ngModel',
link : function (scope, element, attrs, ngModelCtrl) {
$(function(){
element.datepicker({
dateFormat: 'mm/dd/yy',
showStatus: true,
showWeeks: true,
highlightWeek: true,
maxDate: 0,
numberOfMonths: 1,
showAnim: "scale",
showOptions: { origin: ["bottom", "right"] },
onSelect: function (date) {
if (this.id === "MessageDateFrom") {
$("#MessageDateTo").datepicker("option", "minDate", date);
} else if (this.id === "MessageDateTo") {
$("#MessageDateFrom").datepicker("option", "maxDate", date);
}
ngModelCtrl.$setViewValue(date);
scope.$apply();
}
});
});
}
}
});
HTML:
<div class="form-group">
<input type="text" id="MessageDateFrom" class="form-control dates" ng-model="messagesForm.dateFrom" datepicker readonly="readonly" />
</div>
<div class="form-group">
<input type="text" id="MessageDateTo" class="form-control dates" ng-model="messagesForm.dateTo" datepicker readonly="readonly" />
</div>
Failing JQuery I've attempted:
$(document).ready(function() {
$("MessageDateTo").datepicker("option","minDate",$("MessageDateFrom").val());
};
Any ideas?
Thanks!
See Question&Answers more detail:os