Using angular $ asyncValidators with a cache

I have a validation directive that checks the value against the endpoint

App.directive('validate', function(fooService, $q) {
  return {
    restrict: "A",
    require: "ngModel",
    link: function(scope, elem, attrs, ngModel) {
      ngModel.$asyncValidators.async = function(modelValue, viewValue) {
        return fooService.get(viewValue)
        .then(function(resp) {
          if (!resp.data.success) {
            return $q.reject('Not found');
          } else {
            return true;
          }
        });
      };
    }
  };
});

Is there a way to cache the previous results of this call and verify them before making an AJAX call?

+4
source share
1 answer

Of course, you can save the result in some kind of variable, for example:

App.directive('validate', function(fooService, $q) {

    var previousResults = {};

    return {
        restrict: "A",
        require: "ngModel",
        link: link
    };

    function link(scope, elem, attrs, ngModel) {
        ngModel.$asyncValidators.async = validateAsync;

        function validateAsync(modelValue, viewValue) {
            var previousResult = previousResults[viewValue];

            if(angular.isDefined(previousResult){
                var method = (previousResult === true) ? 'resolve' : 'reject';
                return $q[method](previousResult);
            }else{
                return fooService.get(viewValue)
                    .then(onSuccess)
                    .catch(onError);
            }

            function onSuccess(resp){
                return previousResults[viewValue] = !!resp.data.success;
            }

            function onError(){
                return previousResults[viewValue] = false;
            }
        }
    }
});

Note that in AngularJS <1.4 $ q.resolve, $ q.when was called.

+3
source

Source: https://habr.com/ru/post/1620201/


All Articles