I have recently developed a new directive:
app.directive("customDate", ['$filter', function ($filter) {
return {
restrict: 'A',
require: '?ngModel',
link: function (scope, element, attributes, controller) {
scope.$watch(function () {
return controller.$modelValue;
},
function (newVal, oldVal) {
if (newVal !== oldVal && newVal) {
var format = attributes.date || "dd-MM-yyyy";
var parsedDate = new Date(newVal);
parsedDate = $filter('date')(newVal, format);
controller.$setViewValue(parsedDate);
controller.$setPristine();
controller.$render();
}
});
}
}
}])
To use this new directive, simply include it in your HTML like so:
<form name='myForm'>
Date: <input type="text" data-ng-model="event.Date" name="Date" custom-date />
</form>
In my scope, I have a handy function that determines the save button's state:
scope.canSave = function () {
return scope.myForm.$valid && scope.myForm.$dirty;
}
Interestingly, despite calling controller.$setPristine()
in the directive, the form controller does not register this change. This results in form.$dirty
being true, while form.Date.$dirty
remains false.
Why is this happening and what steps can be taken to ensure that Date
is recognized as clean by the form?