I have created this directive:
app.directive("date", ['$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();
}
});
}
}
}])
I this directive like this:
<form name='myForm'>
Date: <input type="text" data-ng-model="contract.StartDate" name="StartDate" date />
</form>
In my scope I have a function which determines the state of the save button:
scope.canSave = function () {
return scope.contractForm.$valid && scope.contractForm.$dirty;
}
As you can see in the code snippet of the date
directive, I set controller.$setPristine()
, however this action is not seen by the form controller, because form.$dirty
is set to true
, but when I check form.StartDate.$dirty
it is set to false
.
How is this possible and how can I make sure / force that form
sees that StartDate
is not dirty?
I finally find a solution in the form of parsers and formatters:
app.directive("date", ['$filter', function ($filter) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attributes, controller) {
controller.$parsers.unshift(function (value) {
if (!value) {
return;
}
var format = attributes.date || "dd-MM-yyyy";
return $filter('date')(value, format);
})
controller.$formatters.unshift(function (value) {
if (!value) return;
var format = attributes.date || "dd-MM-yyyy";
return $filter('date')(value, format);
})
}
}
}])