当用户在文本框中输入用户名时,该指令将检查用户名是否已存在或在数据库中可用。如果用户存在,则文本框旁边会显示一条警告,提示“用户已存在”。如果它不存在,则会显示“用户名可用”的警告。
我的问题是,当我在文本框中输入现有用户名时,它只显示任何内容,但是当我输入数据库中不存在的用户名时,它会显示“用户名存在”。为什么会这样?
uniqueUsers.php
<?php
$app->get('/uniqueUsername/:username', function ($username) {
$status_code = 200;
$resp = array('status'=>'success','message'=>'Query Success','data'=>null);
$resp['data'] = User::find_by_active_and_username('1',$username);
if(is_object($resp['data'])){
$resp['data'] = $resp['data']->to_array();
}
else{
$resp['data'] = objToArr($resp['data']);
}
JSONResponse($status_code,$resp);
});
指令:usernameavailable.js
angular.module('installApp')
.directive('usernameAvailable', function ($http, $timeout) {
return {
restrict: 'AE',
require: 'ngModel',
link: function(scope, elm, attr, model) {
model.$asyncValidators.usernameAvailable = function(username) {
return $http.get('../api/v1/uniqueUsername'+'/'+username).then(function(res){+
$timeout(function(){
model.$setValidity('usernameAvailable', !!res.data);
}, 1000);
});
};
}
};
});
HTML:accounts.html
<input type="text" name="username" ng-model="username" username-available required ng-model-options="{ updateOn: 'blur' }">
<div ng-if="myForm.$pending.usernameAvailable">checking....</div>
<div ng-if="myForm.$error.usernameAvailable">Username available</div>
请帮忙。在此先感谢: - )
答案 0 :(得分:1)
使用ng-messages
指令,例如here
<div ng-if="myForm.username.$dirty">
<div ng-messages="myForm.username.$error" class="validation-error">
<div ng-message="required">Username required</div>
<div ng-message="username">Username already in use</div>
</div>
<div ng-messages="myForm.username.$pending" class="validation-pending">
<div ng-message="username">Checking username availability...</div>
</div>
</div>