[英]asyncvalidator promise not being resolved
我正在嘗試取消$ asyncValidator承諾,但是拋出未定義錯誤,這是我的代碼:
(function () {
'use strict';
angular
.module("webclient.common.directives")
.directive("duplicateModelNameValidator",
["$q",
"modelManager",
duplicateModelNameValidator
]);
function duplicateModelNameValidator($q, modelManager) {
return {
restrict: "A",
require: "ngModel",
link: function (scope, element, attrs, ngModel) {
var classId = attrs.duplicateModelNameValidator;
ngModel.$asyncValidators.duplicateModelName = function (modelValue) {
var defer = $q.defer();
//if the user hasn't touched the input box I don't want to call the database code
if (ngModel.$pristine)
//I want to resolve the promise but get the error below?
return defer.resolve();
modelManager.find(modelValue, false).then(function (data) {
if (data.exists === true)
// Found a row
return defer.reject();
else
// Did not find a row
return defer.resolve();
});
return defer.promise;
}
}
}
}
}());
代碼拋出錯誤:
[ngModel:nopromise]期望異步驗證器返回一個Promise,但改為'undefined'。
謝謝
方法defer.resolve()
和defer.reject()
控制defer.reject()
的狀態,它們不返回promise,而驗證函數defer.promise
返回promise。 您應該使用方法$q.when()
和$q.reject()
代替:
ngModel.$asyncValidators.duplicateModelName = function (modelValue) {
//if the user hasn't touched the input box I don't want to call the database code
if (ngModel.$pristine) {
return $q.when(true);
}
return modelManager.find(modelValue, false)
.then(function (data) {
if (data.exists === true) {
// Found a row
// this will reject the promise returned by modelManager.find()
return $q.reject('exists');
}
// Did not find a row
// no need to do anything, this promise is already
// resolved which will succeed the validation
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.