有几个问题出现了。首先,我该如何在模板中捕获错误,因为即使响应是404并且正确的代码被执行,has-error
类也不会被应用。
其次,这只在第一次有效。如果我离开该字段然后再次输入,每次按键时都会出现 TypeError: validator is not a function
异常(正如您在代码中所看到的,我仅在 blur
上执行此操作)。我做错了什么?
服务调用
this.CheckIfUnique = function(code) {
var deferred = $q.defer();
$http.get("/Api/Codes/Unique/" + code).then(function() {
deferred.resolve();
}, function() {
deferred.reject();
});
return deferred.promise;
};
该指令
var uniqueCode = [ "CodeService", function(codeService) {
return {
restrict: "A",
require: "ngModel",
link: function(scope, element, attrs, ctrl) {
element.bind("blur", function(e) {
if (!ctrl || !element.val()) return;
var currentValue = element.val();
ctrl.$asyncValidators.uniqueCode = codeService.CheckIfUnique (currentValue);
});
}
};
}];
codeModule.directive("uniqueCode",uniqueCode);
The HTML
<div class="form-group" ng-class="{'has-error' : ( codeForm.submitted && codeForm.code.$invalid ) || ( codeForm.code.$touched && codeForm.code.$invalid ) }">
<label class="col-md-4 control-label" for="code">Code</label>
<div class="col-md-8">
<input class="form-control" id="code" name="code" ng-model="newCode.code" ng-required="true" type="text" unique-code />
<span class="help-block" ng-show="( codeForm.submitted && codeForm.code.$error.required ) || ( codeForm.code.$touched && codeForm.code.$error.required)">Please enter a code</span>
<span class="help-block" ng-show="codeForm.code.$pending.code">Checking if the code is available</span>
<span class="help-block" ng-show="( codeForm.submitted && codeForm.code.$error.uniqueCode ) || ( codeForm.code.$touched && codeForm.code.$error.uniqueCode)">This code already exist</span>
</div>
</div>
MVC 控制器
public async Task<ActionResult> Unique(string code)
{
if (string.IsNullOrWhiteSpace(code))
{
return new HttpStatusCodeResult(HttpStatusCode.NotFound);
}
return _db.Codes.Any(x => x.Code = code)
? new HttpStatusCodeResult(HttpStatusCode.NotFound)
: new HttpStatusCodeResult(HttpStatusCode.Accepted);
}
编辑:
为了澄清,API仅在我离开字段时调用,异常在按键时抛出(仅在第一次离开字段后)。
编辑2:
如果有人错过了评论,dfsq的答案有效,如果您在输入框中添加ng-model-options="{ updateOn: 'blur' }"
,它将仅在blur
上验证。
resolve()
的调用应该放在成功回调函数中而不是失败回调函数中吗? - MourndarkcodeForm.$submitted
;-) - Mourndarklink
上设置断点,您应该能够在验证发生的时候(至少在Chrome中)看到DOM的快照,包括动态表单类,这可能有助于诊断它。 - Mourndark