Reputation: 6188
I'm validating an input element with the directive below. The problem is that this way it's only executed when the input element is activated. Is there a way to force execute the parsers methods of all input elements of a form?
"use strict";
angular.module("kap.directive")
.directive('kapValidationDuration', ['$timeout', '$log', function ($timeout, $log) {
return {
restrict: 'A',
require: 'ngModel',
scope: { minReservationDurationMinutes: '=minReservationDurationMinutes' },
link: function (scope, element, attrs, ctrl) {
if (attrs.type === 'radio' || attrs.type === 'checkbox') {
return;
}
ctrl.$parsers.push(function (value) {
if(value && !element[0].hidden) {
var lTimeValues = value.split(":"),
lHoursToMinutes = parseInt(lTimeValues[0], 10) * 60,
lMinutes = parseInt(lTimeValues[1], 10),
lMinReservationDurationMinutes = parseInt(attrs.minreservationdurationminutes, 10) || 10,
lValidity = true;
if ((lHoursToMinutes + lMinutes) < lMinReservationDurationMinutes) {
lValidity = false;
}
ctrl.$setValidity('kapValidationDuration', lValidity);
}
return value;
});
}
};
}]);
Upvotes: 0
Views: 60
Reputation: 40296
In order to do that, i.e. validate the initial values as well, you also have to use the $formatters
. Luckilly, in your case, you just have to unshift
the same function to the $formatters
, as the one used for the $parsers
.
The reason is that the parsers are used when going form → model. In general this means data conversion: if the model was a number, the input from the user is always a string and has to be converted; the errors may not only be validation (e.g. "age must be positive") but also parsing (e.g. "'tata' is not a valid number"). The formatters when going model → form. This is, as the name implies, formatting: e.g. a Date
object may need to be displayed as dd/MM/yyyy
in my locale (greek), but MM/dd/yyyy
in other locales.
See this fiddle: http://jsfiddle.net/52dAB/
In the fiddle I am still using two separate functions for the formatters and the parsers, despite them being identical in implementation. Just for the sake of generality.
Upvotes: 1