asyncvalidator承诺没有得到解决

时间:2016-06-09 11:04:06

标签: javascript angularjs

我正在尝试取消$ 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'。

由于

1 个答案:

答案 0 :(得分:2)

方法defer.resolve()defer.reject()控制defer.promise的状态,他们 NOT 返回承诺,而验证函数则返回承诺。您应该使用方法$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
        });
}