尝试将 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);
}
}
});
}
}
}])