I am making a date range angular directive. This uses two ui.bootstrap date pickers for the start and end dates.
I am watching the start and end dates to adjust them if one of the selected dates goes further than 3 months from the other.
The models update correctly, as I can see them update when printed directly to the screen, however the dates within the text fields does not.
My guess is that the text field date is not directly tied to the model and requires a function to be run to update the text field.
The example directive code is given below, and is functional within a plunker.
var app = angular.module('app', ['ui.bootstrap']);
app.directive("dateRange", function() {
return {
restrict: "A",
templateUrl: "date-range.html",
controller: [
"$scope",
"$attrs",
"$element",
function($scope, $attrs, $element) {
// Watch the start/end dates for external changes.
// If they get too far apart, modify the other date to bring it inline.
$scope.$watch("dateRange.start", function(startDate) {
var max = new Date(startDate);
max.setMonth(startDate.getMonth() + 3);
if ($scope.dateRange.end.getTime() > max.getTime()) {
$scope.dateRange.end.setTime(max.getTime());
}
});
$scope.$watch("dateRange.end", function(endDate) {
var min = new Date(endDate);
min.setMonth(endDate.getMonth() - 3);
if ($scope.dateRange.start.getTime() < min.getTime()) {
$scope.dateRange.start.setTime(min.getTime());
}
});
$scope.dateRange = {
start: (function() {
var date = new Date();
date.setMonth(date.getMonth() - 1);
return date;
})(),
end: new Date(),
};
}
]
};
});
app.directive("datePicker", function() {
return {
restrict: "A",
scope: {
model: "=model",
label: "@label"
},
templateUrl: "date-picker.html",
controller: [
"$scope",
"$attrs",
"$element",
function($scope, $attrs, $element) {
$scope.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
$scope.format = "dd-MM-yyyy";
}
]
};
});