0

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

TypeError:无法设置未定义的属性“用户名”。

如何定义 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);
	                }
	            }
	            
	        });
	    }

	}
}])

4

2 回答 2

2

$asyncValidators可从 angularjs 1.3 及更高版本获得:

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

于 2014-11-28T13:05:55.213 回答
-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;
                    }
                );
            };
        }
    };
});
于 2014-11-17T15:47:12.693 回答