In my Angular application, I have a form that undergoes custom validation on all fields whenever there is a change in any field. This means that the validity of each field can change based on the values of other fields in the form, resulting in the entire form being validated with every edit.
Although the validation functions correctly, I am facing an issue where the form field being edited loses focus every time the validation is triggered (such as with each key-press). I suspect that this problem is due to a flaw in the validator implementation that I had copied from the internet months ago and now can't locate.
This issue occurs specifically in Chrome, but not in IE9.
Here is the snippet of the implementation. Can anyone spot any obvious mistakes that could be causing the focus problems I am experiencing?
angular.module('myComponent').directive('myValidator', function (MyApiResource) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, ele, attrs, ctrl) {
function myValidator(value) {
if (value) {
var myObject = JSON.parse(JSON.stringify(scope.myObject));
myObject[attrs.name] = value;
MyApiResource.validate(myObject, function (uiValidationFailures) {
for (var attributeName in myObject) {
if (scope.correctionForm[attributeName]) {
var valid = !uiValidationFailures.filter(function (el) { return el.AttributeName === attributeName; }).length;
scope.correctionForm[attributeName].$setValidity('myValidator', valid);
if (valid && attributeName !== attrs.name && scope.correctionForm[attributeName].$pristine) {
scope.correctionForm[attributeName].$setViewValue(myObject[attributeName]);
}
scope.uiValidationFailures[attributeName] = valid
? undefined
: uiValidationFailures.filter(function (el) { return el.AttributeName === attributeName; });
}
}
return value;
});
return value;
}
scope.uiValidationFailures[attrs.name] = undefined;
return undefined;
};
ctrl.$parsers.unshift(myValidator);
ctrl.$formatters.unshift(myValidator);
}
}
});