我正在使用表单验证指令。每次更改用户名字段都会发出一个 http 请求。我可以在控制台中看到请求发生了,但是在字段发生模糊事件之前,视图不会使用“唯一”错误消息进行更新。
但是,只要将用户名从重复更改为唯一用户名,错误消息就会立即消失。在这个方向上不需要模糊(隐藏错误消息),只在另一个方向(显示错误消息)......
这是为什么?
======= 指令 =========
myDirs.directive('ensureUnique', ['$http', function($http) {
return {
require: 'ngModel',
link: function(scope, ele, attrs, c) { if (scope.registered) {return true};
scope.$watch(attrs.ngModel, function() {
$http({
method: 'GET',
url: 'http://webservice.buddyplatform.com/v1/UserAccount_Profile_CheckUserName',
params: {
UserNameToVerify: ele.val(),
BuddyApplicationName:'xxx',
BuddyApplicationPassword:'yyy'
}
}).success(function(data, status, headers, cfg) {
c.$setValidity('unique', (data==='UserNameAvailble'));
}).error(function(data, status, headers, cfg) {
c.$setValidity('unique', false);
});
});
}
}
}]);
=========== HTML ================
<label>Username:</label>
<input name="username" type="text" ng-model="form.username"
ng-minlength=5 ng-maxlength=20 ensure-unique="username" required/>
<div class="error" ng-show="myForm.username.$dirty && myForm.username.$invalid">
<small class="error" ng-show="myForm.username.$error.required">Please input a username</small>
<small class="error" ng-show="myForm.username.$error.minlength">Your username is required to be at least 5 characters</small>
<small class="error" ng-show="myForm.username.$error.maxlength">Your username cannot be longer than 20 characters</small>
<small class="error" ng-show="myForm.username.$error.unique">That username is taken, please try another</small>
</div>