I have the following directive:
.directive('validateAsync',
['$http', 'API_LOCATION', function($http, API_LOCATION) {
return {
require : 'ngModel',
link : function(scope, element, attrs, ngModel) {
var apiUrl = attrs.validateAsync;
function setAsLoading(bool) {
ngModel.$setValidity('asyncLoading', !bool);
}
function setAsAvailable(bool) {
ngModel.$setValidity('asyncAvailable', bool);
}
ngModel.$parsers.push(function(value) {
if(!value || value.length == 0) return;
setAsLoading(true);
setAsAvailable(false);
$http.get(API_LOCATION + apiUrl, {
params: {
value : value
}
})
.success(function() {
setAsLoading(false);
setAsAvailable(true);
})
.error(function() {
setAsLoading(false);
setAsAvailable(false);
});
return value;
})
}
}
}]);
Which is called like this:
<input ... validate-async="api/endpoint/to/check/validity">
It works great, actually too great. As it fires of a request on every keydown.
How could I make the directive wait like 300 ms before validating the input or make it fire the validation on input blur ?
Update
It was easier than I though:
adding ng-model-options="{ debounce: 300 }" did the trick.
Thanks JB Nizet for leading me to the right answer