我正在尝试编写指令来验证服务器上是否存在用户名。如果存在,我想通过 ng-messages 显示错误。但由于某种原因,错误没有显示出来。我检查了服务器响应,它返回了正确的值,但看起来验证器无法解析承诺左右......
//Directive
angular.module('main').directive('checkIfUserExists', checkIfUserExists);
checkIfUserExists.$inject = ['authService'];
function checkIfUserExists(authService) {
return {
require: "ngModel",
link: function (scope, element, attributes, ngModel) {
ngModel.$asyncValidators.checkIfUserExists = function (modelValue) {
return authService.suchUserAlreadyExists(modelValue);
};
}
};
};
//service method
suchUserAlreadyExists: function (user) {
return $http.get(baseUrl + "/api/account/someone/" + user).then(function (response, status, headers, config) {
console.log(response.data);
return !response.data;
},function (data, status, headers, config) {
return $q.reject('error occured');
});
}
//Input I want to validate
<div class="col-md-6">
<div class="row">
<div class="col-md-8">
<input type="text" check-if-user-exists ng-pattern="/^[a-zA-Z0-9]*$/" ng-maxlength="10" ng-minlength="6" class="form-control" id="username" name="username" ng-model="general.username" placeholder="******" required />
</div>
</div>
<div class="row">
<div class="col-md-12 inputErrorMessage">
<div ng-messages="registerGeneralForm.username.$error" ng-if="registerGeneralForm.username.$dirty">
<div ng-message="required">This field is required</div>
<div ng-message="pattern">Only alphanumeric characters allowed</div>
<div ng-message="maxlength">Username cannot exceed 10 characters</div>
<div ng-message="minlength">Username must be over 6 characters</div>
<div ng-message="checkIfUserExists">Such user already exists</div>
</div>
</div>
</div>
</div>
任何想法为什么它不起作用?感谢您的任何帮助