I have a form where some inputs are connected to a custom validator using a directive. The input must be checked for blur, and does so through an asynchronous call to the REST API.
HTML:
<input type="text" validate-this ng-model="thisField" ng-model-options="{'updateOn': 'blur'}" ng-pattern="some pattern" />
Directive (abbreviated for brevity):
return { access: 'A', require: 'ngModel', scope: false, link: function (scope, elem, attrs, ngModel) { ngModel.$asyncValidators.validateThis = function (modelVal, viewVal) { if (!modelVal && !viewVal) return $q.defer().promise;
The above code works fine, but pay attention to the hacker line directly below the signature of the verification function:
if (!modelVal && !viewVal) return $q.defer().promise;
Without this line, Angular tries to check the field immediately when the application loads, and not just for blurring. This is a problem because the actual verification code does some string parsing, and since both modelVal and viewVal are undefined , JavaScript throws an error.
I tried disabling functionality that loads data into fields when the application loads, and the error still occurs. However, the template specified in ng-pattern does , respects my wishes and checks only for blurring the field - it does NOT try to check for page loading. Is there a way to tell Angular to only check for blur, or make it stop trying to check as soon as the page loads? Or am I using $asyncValidators ?
javascript angularjs
Mike Oct 27 '14 at 2:49 a.m. 2014-10-27 14:49
source share