angularjs 1.2中的异步验证

时间:2015-01-11 14:31:25

标签: javascript angularjs validation

我正在尝试创建一个电子邮件存在验证指令,该指令进行ajax调用以查看是否存在电子邮件。我无法使用此代码更新该字段的验证。

app.directive('uniqueValidator', ['UniqueValidatorService',function(uniqueValidatorService) 
    {
        var linkFn=function(scope, elem, attrs,ngModel)
        {
            var vm=this;
            vm.ngModel=ngModel;
            vm.scope=scope;
            var config=scope.$eval(attrs.uniqueValidator);
            console.log('Value of the atribute'+window.angular.toJson(config));
            /*If the value is truly unique then we would want to set validation as passed*/
            vm.successCallback=function successCallback(unique){
                vm.ngModel.$setValidity('unique',false);
                console.log('Value of validity success case'+vm.ngModel.$valid);
            };
            /*Set validity as false to make sure we have a */
            vm.errorCallback=function errorCallback(error){
                 ngModel.$setValidity('unique',true);
                 console.log('Value of validity'+ngModel.$valid);
            };
            var blurHandler=function(event){
                console.log('In blur'+ngModel);
                 if (!ngModel || !elem.val()) return;
                var currentValue=elem.val();
                uniqueValidatorService.checkUniqueness(config.url,config.property,currentValue).then(function(data){
                    vm.successCallback(data);

                },function(error){vm.errorCallback(error)});
            }
            elem.bind('blur',blurHandler.bind(vm));

        };
        return {
            restrict: 'A',
            scope:{},
            require:'ngModel',
            link: linkFn
        };
    }
    ])
    .directive('uniqueErrorMessage',function(){
        var linkFn= function(scope, elem, attrs,ngModel){
            scope.message='Email is in use';
            console.dir(scope.registrationForm.email.$error);
        };
         return {
            restrict: 'E',
            replace:true,
            template:'<span ng-show="registrationForm.email.$dirty && registrationForm.email.$error.unique" >{{message}}</span>',
            link: linkFn
        };

        });

根据验证结果,唯一错误消息指令未正确更新。即使验证通过,它仍会显示在DOM上。此外,我发现即使验证失败,对输入元素有效的ngModel。$也是如此。我已经尝试将$ setValidity封装在一个范围内。$ apply但是这会导致摘要正在进行中错误。这有任何帮助我很感激。我将无法包含ui路由器验证或升级我的angularjs版本以使用更新的验证框架

谢谢, 拉胡

1 个答案:

答案 0 :(得分:3)

以下是一个可能有用的示例:

var app = angular.module('app', []);
app.controller('ctrl', function() {});

app.directive('unique', function(userFactory) {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attr, ngModelController) {
      element.on('blur', function() {
        if (ngModelController.$viewValue != '') {
          userFactory.tryUsername(ngModelController.$viewValue)
            .then(
              function succcess(result) {
                ngModelController.$setValidity('unique', true);
              },
              function fail(result) {
                ngModelController.$setValidity('unique', false);
              }
            );
        }
      });
    }
  }
});

app.factory('userFactory', function($q) {
  return {
    tryUsername: function(username) {

      var deferred = $q.defer();
      if (username == 'john')
        deferred.reject('john already exists!');
      else if (username == 'tim')
        deferred.resolve('tim');
      else if (username == 'hank')
        deferred.reject('hank already exists!');
      else
        deferred.resolve(username);

      return deferred.promise;
    }
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="app" ng-controller="ctrl">
  <form name="form">
    Enter a Username (john and hank are taken):
    <br />
    <input type="text" ng-model="username" name="username" unique /> <span ng-show="form.username.$error.unique">Username is taken!</span><br />
    {{ form.username.$error }}
  </form>
</body>