0

我正在尝试编写指令来验证服务器上是否存在用户名。如果存在,我想通过 ng-messages 显示错误。但由于某种原因,错误没有显示出来。我检查了服务器响应,它返回了正确的值,但看起来验证器无法解析承诺左右......

//Directive

angular.module('main').directive('checkIfUserExists', checkIfUserExists);

checkIfUserExists.$inject = ['authService'];

function checkIfUserExists(authService) {
    return {
        require: "ngModel",
        link: function (scope, element, attributes, ngModel) {

            ngModel.$asyncValidators.checkIfUserExists = function (modelValue) {
                return authService.suchUserAlreadyExists(modelValue);
            };
        }
    };
};

//service method

  suchUserAlreadyExists: function (user) {
            return $http.get(baseUrl + "/api/account/someone/" + user).then(function (response, status, headers, config) {
                console.log(response.data);
                return !response.data;
            },function (data, status, headers, config) {
                return $q.reject('error occured');
            });
        }
//Input I want to validate

 <div class="col-md-6">
     <div class="row">
            <div class="col-md-8">
               <input type="text" check-if-user-exists ng-pattern="/^[a-zA-Z0-9]*$/" ng-maxlength="10" ng-minlength="6"                                   class="form-control" id="username" name="username" ng-model="general.username" placeholder="******"                                 required />
            </div>
            </div>
            <div class="row">
                <div class="col-md-12 inputErrorMessage">
                    <div ng-messages="registerGeneralForm.username.$error" ng-if="registerGeneralForm.username.$dirty">
                        <div ng-message="required">This field is required</div>
                        <div ng-message="pattern">Only alphanumeric characters  allowed</div>
                        <div ng-message="maxlength">Username cannot exceed 10 characters</div>
                        <div ng-message="minlength">Username must be over 6 characters</div>
                        <div ng-message="checkIfUserExists">Such user already exists</div>
                    </div>
                </div>
            </div>
        </div>

任何想法为什么它不起作用?感谢您的任何帮助

4

1 回答 1

0

$asyncValidators 函数的返回值必须是一个承诺。承诺的拒绝“失败”验证,承诺的解决“通过”验证。在这里工作小提琴。

var myApp = angular.module('myApp', ['ngMessages']);

myApp.controller('MyCtrl', ['$scope',
  function($scope) {}
]);

myApp.directive('checkIfUserExists', [
  '$q',
  '$http',
  function($q, $http) {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, element, attributes, ngModel) {
        ngModel.$asyncValidators.checkIfUserExists = function(modelValue) {
          var defer = $q.defer();
          $http.get(baseUrl + "/api/account/someone/" + user).then(function(isUnique) {
            if (response.data) {
              defer.resolve();
            } else {
              defer.reject();
            }
          }).catch(function(err) {
            // reject with the error message
            defer.reject(err);
          });
          // return the promise
          return defer.promise;
        };
      }
    };
  }
]);
<section ng-controller="MyCtrl">
  <ng-form name="registerGeneralForm">
    <input type="text" check-if-user-exists id="username" name="username" ng-model="general.username" placeholder="******" />
    <div ng-messages="registerGeneralForm.username.$error" ng-show="registerGeneralForm.username.$dirty">
      <div ng-message="checkIfUserExists">Such user already exists</div>
    </div>
  </ng-form>

于 2016-04-14T19:47:01.397 回答