gpt4 book ai didi

javascript - 将 Angular $asyncValidators 与缓存一起使用

转载 作者:搜寻专家 更新时间:2023-10-31 08:26:28 25 4
gpt4 key购买 nike

我有一个验证指令,用于根据端点检查值

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;
}
});
};
}
};
});

有没有办法缓存该调用的先前结果并在执行 AJAX 调用之前检查这些结果?

最佳答案

当然,您可以将结果保存在某种变量中,如下所示:

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;
}
}
}
});

请注意,在 AngularJS < 1.4 中,$q.resolve 被称为 $q.when。

关于javascript - 将 Angular $asyncValidators 与缓存一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34299301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com