4

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

5
  • 3
    docs.angularjs.org/api/ng/directive/ngModelOptions Commented Aug 21, 2015 at 10:24
  • Thanks alot - was easier than i thought Commented Aug 21, 2015 at 10:30
  • @JB Nizet Great solution Commented Aug 3, 2017 at 7:18
  • @RVandersteen If you found a solution, you should post it as an Answer and mark it as Accepted. Commented Mar 20, 2018 at 15:34
  • There you go ;) Commented Mar 20, 2018 at 15:46

1 Answer 1

3

It was easier than I though: adding ng-model-options="{ debounce: 300 }" did the trick.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.