我正在使用form-validation-as-you-type的指令。每次更改用户名字段时都会发出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>
答案 0 :(得分:0)
摘要周期很棘手,但据我所知,成功是在摘要周期内,之后没有新的摘要周期。因此设置有效性并不意味着会有另一个摘要。有几种方法可以解决这个问题。最简单的方法是使用$timeout
服务。为此,请将$timeout
注入您的指令,然后更改代码:
$timeout(function(){c.$setValidity('unique', (data==='UserNameAvailble'));});
您也可以使用$ apply或手动触发$ digest来执行此操作。但是如果你不同步,这两种方法都会触发错误。 $ timeout不是那么快,因为它总是触发另一个摘要,即使不需要一个摘要。有很多与摘要,周期等有关的问题。这个问题特别相关:Angular JS: Chaining promises and the digest cycle