Angular JS自定义验证$ asyncvalidator未定义

时间:2014-11-17 15:36:41

标签: javascript angularjs angularjs-directive angularjs-validation

尝试将asyncvalidator添加到我的自定义用户名验证程序中。但是它会输出错误:

TypeError:无法设置属性' username'未定义的。

如何定义asyncvalidator?我以为我会自动由NgModel控制器?



<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
angular.module('myApp.commonDirectives', ['myApp.services']).directive('username', ['UsernameService',function(UsernameService){
	
	return {
		
	    restrict: 'A',
	    require: "ngModel",
	    scope: {
	        hasFocus: "=username"
	        
	    },
	    link: function(scope, element, attrs, ctrl) {
	    
	        scope.$watch('hasFocus', function(hasFocus) {
	            if(angular.isDefined(hasFocus)) {

	                // on blur
	                if(!hasFocus) {
	                    
	                  
	                    ctrl.$validated=false;
	                    ctrl.$asyncValidators.username = function(value){
	                    UsernameService.validate(value)
	                        .then(function(resolvedData) {
	                            if(resolvedData) {
	                          
	                            	ctrl.$validated=true;
	                                ctrl.$setValidity('checking', true);
//	                                ctrl.$setValidity('username', true);
	                            }
	                            else {
	                          
	                            	ctrl.$validated=true;
	                                ctrl.$setValidity('checking', false);
//	                                ctrl.$setValidity('username', false);
	                            }
	                        }
	                     );
	                }
	                }
	                
	                // on focus
	                else {
	                    ctrl.$setValidity('username', true);
	                    ctrl.$setValidity('checking', true);
	                }
	            }
	            
	        });
	    }

	}
}])
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

$asyncValidators可从angularjs 1.3及以上版本获得:

https://code.angularjs.org/1.2.27/docs/api/ng/type/ngModel.NgModelController

答案 1 :(得分:-1)

try  something like this :

angular.module('myModule').directive('usernameValidator', function($http, $q) {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            ngModel.$asyncValidators.username = function(modelValue, viewValue) {
                return $http.post('/username-check', {username: viewValue}).then(
                    function(response) {
                        if (!response.data.validUsername) {
                            return $q.reject(response.data.errorMessage);
                        }
                        return true;
                    }
                );
            };
        }
    };
});