从$ asyncValidators服务器serponse设置表单/输入字段无效

时间:2015-07-06 10:51:22

标签: angularjs angular-resource

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

1 个答案:

答案 0 :(得分:2)

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

我从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秒的小延迟,表示用户名已被占用。