AngularJS | $ setValidity не работает

0

Я хочу получить недопустимый ввод, если переменная (emailIsAvailable) истинна или ложна. Прямо сейчас, когда переменная 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;
      });
    }
  };
  • 0
    использовать $asyncValidators было бы идеально здесь, создав директиву
Теги:

1 ответ

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>

Ещё вопросы

Сообщество Overcoder
Наверх
Меню