尽管您找到了答案,但我正在使用您的测试用例发布异步验证器的综合示例。
angular.module('myModule').directive('nameValidator', function($http, $q) {
return {
restrict: 'A',
require: 'ngModel',
scope: {
edit: '=',
},
link: function(scope, element, attrs, ngModel) {
ngModel.$asyncValidators.uniqueCode = function() {
return $http.post('/checkFunc', {name: scope.edit}).then(
function(response) {
if (!response.data.validUsername) {
//invalid case ..validation failed
return $q.reject(response.data.errorMessage);
}
return true;
}
);
};
}
};
});
要使用这个 -
<input type="text" ng-model="username" required name-validator>
其他不使用直接作用域的方法。
.directive('usernameValidator', function($q, $timeout) {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$asyncValidators.username = function(modelValue, viewValue) {
if (!viewValue) {
return $q.when(true);
}
var deferred = $q.defer();
$timeout(function() {
// Faking actual server-side validity check with $http.
// Let's pretend our service is so popular all short username are already taken
if (viewValue && viewValue.length < 5) {
deferred.reject();
}
deferred.resolve();
}, 2000);
return deferred.promise;
};
}
};
});