我想添加一個驗證字段給我的一個輸入,它應該請求服務器輸入的VAT號碼是否有效,所以我使用了一個異步驗證器。正常工作與此代碼:asyncValidator依賴於其他字段的值
myApp.factory('isValidVat', function($q, $http) {
return function(vat) {
var deferred = $q.defer();
console.log(vat);
$http.get('/api/vat/' + vat).then(function() {
deferred.resolve();
}, function() {
deferred.reject();
});
return deferred.promise;
}
});
myApp.directive('validVat', function(isValidVat) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$asyncValidators.vat = isValidVat;
}
};
});
<form name="form" novalidate ng-submit="check(form)">
<div class="vat-field">
<label>VAT number
<input type="text" ng-model="formModel.vat" name="vat" valid-vat="true">
</label>
<div ng-show="registerForm.$submitted || registerForm.vat.$touched">
<span ng-show="registerForm.vat.$error.vat">
<small class="error">Your VAT address is not valid, please correct.</small>
</span>
</div>
</div>
<div class="country-field">
<label>Country
<select ng-model="formModel.country" name="country">
<option value="{{country.iso_3}}" ng-repeat="country in countries()">{{country.name}}</option>
</select>
</label>
</div>
<button type="submit">Check</button>
</form>
不過,我想打另一個字段的值,這asyncValidator檢查條件(國家,尤其是國別是否是歐盟國家)。 國家領域是一個組合框,通過一個服務,其中包含所有國家和他們的油缸信息和歐盟地位的記錄。 但是,我不知道如何將所選國家的價值注入工廠功能。其中一個想法是將選定的國家與自己的服務聯繫起來,並在工廠中使用它,但是當選擇另一個國家時,驗證不會再次運行。如果選擇一個非歐盟國家,我真的不在乎這個領域是什麼。
非常感謝。解決辦法比我想象的容易,現在我覺得很愚蠢:),但是他學到了新的東西。 – Elvin
你不必感到愚蠢。這件事真的有點棘手。如果你深入到驗證中,他們會變得越來越簡單。 –