1

我正在使用指令来进行表单验证。每次更改用户名字段都会发出http请求。我可以在控制台中看到请求发生,但视图不会更新为“唯一”错误消息,直到发生模糊事件。AngularJS指令不按预期更新视图

但是,只要用户名从一个副本更改为一个唯一的,该错误消息立即消失。在这个方向上不需要模糊(隐藏错误消息),只在另一个(显示错误消息)...

这是为什么?

=======指令=========

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

创建一个plunk来显示问题 –

回答

0

摘要周期是棘手的,但据我所知,成功是在摘要周期内,没有新的摘要周期后。所以设置有效性并不意味着会有另一个摘要。有几种方法可以解决这个问题。最简单的方法是使用$timeout服务。要做到这一点,注入$timeout到你的指令,然后更改像这样的代码:

$timeout(function(){c.$setValidity('unique', (data==='UserNameAvailble'));});

你也可以用$做这个应用或通过手动触发$摘要。但是,如果你不同步,这两种方法都会触发错误。 $ timeout没有那么快,因为它总是触发另一个摘要,即使不需要。有很多与摘要,周期等有关的问题。这一个是特别相关:Angular JS: Chaining promises and the digest cycle

+0

我试过这个建议,但令我惊讶的是,问题依然存在。 –