AngularJS |使用ng-blur和条件变量验证电子邮件唯一性

时间:2016-08-18 05:07:48

标签: angularjs

使用ng-blur我在用户可以提交表单之前确认电子邮件地址的唯一性。我希望下面的代码只显示"该电子邮件地址是"当它执行$http.put并收到409(我确认正在发送)时。在所有其他情况下,emailIsAvailable变量应保持为真,我不应该看到"该电子邮件地址已被采取"。不幸的是,错误显示API是发送409还是200。

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>
        <span class="help-block has-error" ng-if="signup.email.$dirty">
          <span ng-show="signup.email.$error.required">Email address is required.</span>
          <span ng-show="signup.email.$error.email">Not a valid email address.</span>
          <span ng-hide="emailIsAvailable">That email address is taken.</span>
        </span>
      </div>
    </div>

控制器:

  $scope.emailIsAvailable = true;

  $scope.validateEmail = function() {

    var email = $scope.signupForm.email;

    console.log(email);

    if (email === undefined) {
      return;
    } else if (AuthService.validateEmail(email) === true) {
      $scope.emailIsAvailable = true;
      return;
    } else {
      $scope.emailIsAvailable = false;
      return;
    }
  };

服务

validateEmail: function (email) {
  return $http.put('/api/user/validateEmail', {
    email : email
  })
  .then(function onSuccess (res) {
    return true;
  })
  .catch(function (res) {
    return false;
  });
}

1 个答案:

答案 0 :(得分:2)

AuthService.validateEmail函数返回一个承诺。

你需要重构你如何称呼它。

$scope.emailIsAvailable = true;

$scope.validateEmail = function() {
  var email = $scope.signupForm.email;

  console.log(email);

  if (email === undefined) {
    return;
  } else {
    AuthService.validateEmail(email)
    .then(function onSuccess (res) {
      $scope.emailIsAvailable = true;
    })
    .catch(function (res) {
      $scope.emailIsAvailable = false;
    });
  }
};