在文档中显示了这个:
ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
var value = modelValue || viewValue;
// Lookup user by username
return $http.get('/api/users/' + value).
then(function resolved() {
//username exists, this means validation fails
return $q.reject('exists');
}, function rejected() {
//username does not exist, therefore this validation passes
return true;
});
};
但是如何将其与输入字段连接?它没有举例说明这一点。
答案 0 :(得分:0)
您可以在指令link
函数中应用验证程序。该指令必须要求ngModel
,然后您将该指令作为属性应用于输入标记。在你的情况下,这可能看起来像这样:
angular.directive('isUniqueName', function () {
return {
require: 'ngModel',
link: function ($scope, $elem, $attrs, ngModel) {
ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
var value = modelValue || viewValue;
// Lookup user by username
return $http.get('/api/users/' + value).
then(function resolved() {
//username exists, this means validation fails
return $q.reject('exists');
}, function rejected() {
//username does not exist, therefore this validation passes
return true;
})
}
}
}
})
然后在您的HTML代码中:
<input type='text' name='username' ng-model='username' is-unique-name />