AngularJS | $ setValidity不起作用

时间:2016-08-18 07:36:33

标签: angularjs

当变量(emailIsAvailable)为true或false时,我希望输入无效。现在,当emailIsAvailable变量为假时......没有任何反应。

HTML:

<div class="form-group" ng-class="{'has-error' : signup.email.$invalid && signup.email.$dirty}">

  <div>
    <input type="text" name="email" class="form-control" placeholder="Email" ng-model="signupForm.email" ng-blur="validateEmail()" required autocomplete="off">
    <span class="help-block has-error" ng-if="signup.email.$dirty">
      <span ng-show="signup.email.$error.emailAvailable" class="help-block has-error">That email address is taken.</span>
    </span>
  </div>
</div>

控制器:

  $scope.validateEmail = function() {

    var email = $scope.signupForm.email;

    console.log(email);

    if (email === undefined) {
      $scope.emailIsAvailable = true;
      return;

    } else {
      AuthService.validateEmail(email)
      .then(function onSuccess (res) {
        $scope.emailIsAvailable = true;
      })
      .catch(function (res) {
        $scope.signupForm.email.$setValidity('emailAvailable', false);
        $scope.emailIsAvailable = false;
      });
    }
  };

1 个答案:

答案 0 :(得分:0)

尝试使用$asyncValidators - https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

angular.module('myApp').directive('emailValid', emailValid);

emailValid.$inject = ['q','AuthService'];

function emailValid($q, AuthService){
   return {
      require: 'ngModel',
      link: function(scope,element,attrs,ngModelCtrl){
         ngModelCtrl.$asyncValidators.emailValid = function(modelValue, viewValue){
            var d = $q.defer();
            var value = modelValue || viewValue;
            if(ngModelCtrl.$isEmpty(value)){
               d.reject(); // invalid
            }else{
               AuthService.validateEmail(value).then(function onSuccess(){
                 // if response valid
                 d.resolve();
               });
            }
            return d.promise;
         }
      }
   };
}

<强> HTML

<div class="form-group" ng-class="{'has-error' : signup.email.$invalid && signup.email.$dirty}">
  <div>
    <input type="text" name="email" class="form-control" placeholder="Email" ng-model="signupForm.email" email-valid required autocomplete="off">
    <span class="help-block has-error" ng-if="signup.email.$dirty">
      <span ng-show="signup.email.$error.emailAvailable" class="help-block has-error">That email address is taken.</span>
    </span>
  </div>
</div>