【发布时间】:2016-07-05 10:37:29
【问题描述】:
我正在通过指令在输入字段上运行自定义异步验证器:
angular.module("app", [])
.directive("accountDescriptionValidator", function ($q, $timeout) {
function startValidation() {
var startValidationDeferred = $q.defer();
$timeout(function() { startValidationDeferred.resolve() }, 100);
return startValidationDeferred.promise;
}
return {
restrict: "A",
require: "ngModel",
scope: {
parentModel: "="
},
link: function (scope, elm, attrs, ctrl) {
ctrl.$asyncValidators["accountDescriptionValidator"] = function (modelValue, viewValue) {
var accountDescriptionValidatorDefer = $q.defer();
startValidation().then(function(accounts) {
if (viewValue == "aaa") {
accountDescriptionValidatorDefer.reject();
}
else {
accountDescriptionValidatorDefer.resolve();
}
});
return accountDescriptionValidatorDefer.promise;
};
}
};
})
验证器做得很好;但是,当验证(正确地)失败时,绑定到输入字段的模型将从其父对象中完全删除。相反,我想要的是在其中保留最新的有效值。这可能吗?
编辑:plnkr 添加了here
EDIT2:现在问题代码与 plnkr 匹配
【问题讨论】:
-
如果您可以使用 jsfiddle 之类的东西添加演示示例,将有助于更好地理解问题并尽早解决。
-
您需要在指令中要求“ngModel”并访问 ngModelController 以修改 $modelValue。
-
@ShaunScovil 如您所见,ngModel 已经是必需的。但是,我将提供一个带有示例的 plunkr;你愿意详细说明你的答案吗?
标签: angularjs validation