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 a
update the minDate
and maxDate
in $timeout
.
$timeout
will make sure that the directive is rendered.
Here is the updated plunker. http://plnkr.co/edit/2ucTcwKFPFpgxoJiRB3f?p=preview
No need to worries about when controller loads or what just add this two property which is minDate & maxDate with there limit like minDate:"-30d",maxDate: 0,
You also can place minDate and maxDate values dynamically from directive property.
Directive
app.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,
minDate:"-30d", //here i did logic -30d
maxDate: 0, //today is max date
numberOfMonths: 1,
showAnim: "scale",
showOptions: { origin: ["bottom", "right"] },
onSelect: function (date) {
ngModelCtrl.$setViewValue(date);
scope.$apply();
}
});
});
}
}
});
Working Plunkr
Update
Sorry for my wrong assumption, If you really do care about whenever the data gets loaded or date variable are assigned at that time jquery ui datepicker
should bind to them, then I'll prefer to use attrs.$observe
which will gets call whenever your attribute expression gets evaluated. For make it working I did added one attribute name loaded="{{messagesForm.dateFrom}}"
& loaded="{{messagesForm.dateTo}}"
on the page so whenever the value gets assigned to dateFrom and dateTo the respective datepicker will get assign to their elements
Directive
app.directive('datepicker', function() {
return {
restrict: 'A',
require : 'ngModel',
link : function (scope, element, attrs, ngModelCtrl) {
//get called when `{{}}` value evaluated
attrs.$observe('loaded',function(val){
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();
}
});
})
}
}
});
Updated Plunkr with demonstration of setting value of scope variables after 5 sec.
Hope this could help you, Thanks.