从 $asyncValidators 服务器 serponse 中设置 form/input 字段无效

Set form/input field invalid from $asyncValidators server serponse

当用户输入他的电子邮件时,我将其发送到服务器以检查它是否正在使用,如果我收到服务器响应错误我想将表单设置为无效并显示消息"emailInUse"

我的指令

ctrl.$asyncValidators.email = function(ctrl, viewValue) {
            return registerResource.emailAvailable.save({"email":viewValue}).$promise.then(
                    function success(response) {
                        // Set the form valid
                    },
                    function error(response) {
                        // Set the form invalid
                    });
        };

我的模板

 <form name="registerForm" ng-submit="vm.register()" role="form">
    <div class="form-group">
        <div>
            <input type="email"
                   placeholder="email"
                   name="email"
                   class="form-control"
                   ng-model="vm.email"
                   email-available
                   ng-minlength=4 ng-maxlength=50 required/>

            <div ng-messages="registerForm.email.$error">
                <div ng-message="required">
                    You forgot to enter your email address...
                </div>
                <div ng-message="email">
                    You did not enter your email address correctly...
                </div>
                <div ng-message="emailInUse">
                    You did not enter your email address correctly...
                </div>
            </div>
        </div>
    </div>

您需要设置一个延迟对象,并根据您的资源成功或错误情况解决或拒绝它。

我从 https://docs.angularjs.org/guide/forms 中获取了示例代码并对其进行了一些更改以匹配您的代码。看这里:

app.directive('emailAvailable', function($q, $timeout) {
  return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {

      ctrl.$asyncValidators.emailInUse = function(modelValue, viewValue) {

        var def = $q.defer();

        registerResource.emailAvailable.save({"email":viewValue}).$promise.then(
          function success(response) {
              // Set the form valid
              def.resolve();
          },
          function error(response) {
              // Set the form invalid
              def.reject();
          });

        return def.promise;
      };
    }
  };
});

我已经更改了 Angular 的示例 plnkr 以便更好地理解:

http://plnkr.co/edit/bfSUcqJONz5QAg6vnZ7O?p=preview

提示: 它使用 $timeout 而不是对后端的 http 调用。但是,如果您输入这些名称之一 var usernames = ['Jim', 'John', 'Jill', 'Jackie'];,它会稍稍延迟 2 秒显示您的用户名已被占用。