Why does adding additional AngularJS validation directives cause $asyncValidators to run multiple times?

前端 未结 3 462
庸人自扰
庸人自扰 2021-01-14 09:52

Why does adding additional AngularJS validation directives cause $asyncValidators to run multiple times on page load?

I created a custom directive which

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-14 10:21

    I followed @New Dev's advice and implemented a simple caching routine which fulfilled my requirement quite nicely, here's what I came up with ..

    link: function (scope, element, attributes, ngModel) {
    
            var cache = {};
            ngModel.$asyncValidators.validateValue = function (modelValue) {
                if (modelValue && cache[modelValue] !== true) {
                    return MyHttpService.validateValue(modelValue).then(function (resolved) {
                        cache[modelValue] = true; // cache 
                        return resolved;
                    }, function(rejected) {
                        cache[modelValue] = false;
                        return $q.reject(rejected);
                    });
                } else {
                    return $q.resolve("OK");
                }
            };
        }
    

提交回复
热议问题