[英]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.