[英]Trigger custom AngularJS form validation on model change
我有一個自定義驗證指令,我用它來確保兩個日期在有效范圍內。 當用戶更改值時,該指令工作正常,但是當我通過AJAX加載新的lineItem
模型時,它不會觸發。
問題是用戶可能在表單上輸入無效日期並觸發錯誤,然后加載另一個lineItem。 此時,即使表單中的數據有效,表單上也會顯示一條錯誤消息。
如果我使用Angular的內置驗證(如required
)嘗試相同的操作,則驗證會觸發並適當地消失。 那么,我需要做什么才能使我的驗證觸發器與Angular相同?
(注意:我在表單屬性上使用novalidate
,而Angular v1.1.5)
指示
ngApp.directive("validateBefore", function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
ctrl.$parsers.unshift(function(value) {
var before = scope.$eval(attrs.validateBefore);
if(value <= before || !before) {
ctrl.$setValidity("validateBefore", true);
return value;
} else {
ctrl.$setValidity("validateBefore", false);
return undefined;
}
});
}
}
});
模板
<div class="date-group">
<span class="date">
<input type="text" class="input-medium" name="starts-at" ng-model="lineItem.startsAt" placeholder="From..." validate-before="lineItem.endsAt">
</span>
<span class="date">
<input type="text" class="input-medium" name="ends-at" ng-model="lineItem.endsAt" placeholder="To..." validate-after="lineItem.startsAt">
</span>
</div>
CONTROLLER
var lineItem = LineItem.get( { id: lineItemId }, function () {
$scope.lineItem = lineItem;
if($scope.lineItemForm) {
$scope.lineItemForm.$setPristine();
}
}
啊哈,我只占了等式的一半。 當輸入從DOM發送到模型時, $parsers
觸發。 我需要添加$formatters
,它將數據從模型發送到DOM。
在$ parsers之后,我添加了以下內容:
ctrl.$formatters.unshift(function(value) {
var before = scope.$eval(attrs.validateBefore);
ctrl.$setValidity("validateBefore", before ? value <= before : true);
return value;
});
這會導致驗證在模型更改時觸發。 這里有更多討論: http : //docs.angularjs.org/guide/forms ,這里http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController#$formatters
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.