My objective is to create a UI Bootstrap datepicker with an input mask feature.
The datepicker
directive only validates dates selected using the popup window and not dates manually typed in by the user. To address this, I researched how to implement custom validation for the text input.
I have successfully implemented all of this in my working Plunk example.
Here are the key components:
<!-- HTML -->
<span>Errors: {{myForm.myDate.$error}}</span>
<input
name="myDate"
type="text"
class="form-control"
ng-class="{error: myForm.myDate.$invalid && myForm.myDate.$dirty}"
datepicker-popup="MM/dd/yyyy"
ng-model="dt"
is-open="opened"
min-date="'09/01/2015'"
max-date="'11/11/2015'"
ng-required="true"
show-weeks="false"
show-button-bar="false" />
// JavaScript
.controller('DatepickerDemoCtrl', function ($scope) {
$scope.dt = undefined;
$scope.open = function($event) {
$scope.opened = !$scope.opened;
};
$scope.today = new Date();
})
.config(function($provide) {
$provide.decorator('datepickerPopupDirective', function($delegate) {
var directive = $delegate[0];
var link = directive.link;
directive.compile = function() {
return function(scope, iEl, iAttrs, ctrls) {
link.apply(this, arguments);
// use custom validator to enforce date range on hand-entered text
ctrls[0].$validators.inDateRange = function(modelValue, viewValue) {
console.log(modelValue, viewValue);
// use the ranges provided in the attributes for the validation
var enteredDate = new Date(viewValue)
, min = new Date(iAttrs.minDate)
, max = new Date(iAttrs.maxDate);
return ctrls[0].$isEmpty(modelValue)
|| (min <= enteredDate && enteredDate <= max);
};
// apply input mask to the text field
iEl.mask('99/99/9999');
};
};
return $delegate;
});
});
Now, I want to make a simple addition by adding a getterSetter
to my input to perform some tasks on the value before saving it to the model.
I update the ng-model
on my element, introduce ng-model-options
to utilize the getterSetter
, and define the actual getterSetter
method.
<!-- HTML -->
ng-model="getSetDate"
ng-model-options="{getterSetter: true}"
// JavaScript
$scope.getSetDate = function(val) {
if(angular.isDefined(val)) {
$scope.dt = val;
} else {
return val;
}
};
However, even in this basic Plunk example featuring the getterSetter
, an error is introduced even though the function does not perform any actions. If I:
- Enter an invalid date, for example,
09/10/2011
- Correct it to a valid date (via typing), for instance,
09/10/2015
- The value disappears
I am unable to determine why the simple addition of this getterSetter
is causing the loss of the value. Should I be implementing this in a different manner?