AngularJS Remote validation
在使用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;
});
};
}
}
});
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!