我有一个自定义验证指令,用于确保两个日期在有效范围内。当用户更改值时该指令工作正常,但是当我通过 AJAX 加载新的 lineItem
模型时它不会触发。
问题是用户可以在表单中输入无效日期并触发错误,然后加载另一个 lineItem。此时,即使表单中的数据有效,表单上也会出现错误消息。
如果我尝试使用 Angular 的内置验证(如 required
)做同样的事情,验证会触发并适当消失。那么,我需要做什么才能使我的验证触发方式与 Angular 的触发方式相同?
(注意:我在表单属性和 Angular v1.1.5 上使用 novalidate
)
指令
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();
}
}
最佳答案
啊哈,我只占了方程式的一半。 $parsers
在输入从 DOM 发送到模型时触发。我需要添加 $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
关于javascript - 在模型更改时触发自定义 AngularJS 表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17408246/