在使用AngularJS进行简单的管理功能模块时,需要对入库数据进行远程唯一性校验,使用directive进行定义,直接作为需要验证的input的属性,eg:<input unique-username>,注意作为属性需要将大写字母处转为 '_lower',具体的说明,暂时没看到。
.directive('uniqueUsername', function($http, $q) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
var value = modelValue || viewValue;
return $http.get('/api/users/' + value).
then(function resolved(data) {
if (!data.data) {
return $q.reject();
}
}, function rejected() {
return true;
});
};
}
}
});