[英]How to display validation errors for array form fields in AngularJS?
我创建了一个动态表单,其中重复的字段作为数组提交。 但是,我想分别验证每个字段并在其旁边显示错误消息。 如果我只有一行,则可以正常工作,但是一旦添加第二行,第一行就会停止显示错误。
<form name='user' id='user' novalidate>
<div ng-repeat="bonus in bonuses">
<input name='codes[]' ng-model="bonus.code" lower-than="{{bonus.end_code}}" />
<input name='end_codes[]' ng-model="bonus.end_code" />
<span class="text-error" ng-show="user['codes[]'].$error.lowerThan">
Code must be less than End Code.
</span>
</div>
</form>
AngularJS
var app = angular.module('newBonus', []);
app.controller('NewBonusController', function($scope) {
$scope.bonuses = [];
$scope.addFields = function () {
$scope.bonuses.push({code:'', end_code: ''});
}
$scope.submit = function(){
console.log($scope.bonuses);
}
});
// Validate that one field is less or equal than other.
app.directive('lowerThan', [
function() {
var link = function($scope, $element, $attrs, ctrl) {
var validate = function(viewValue) {
var comparisonModel = $attrs.lowerThan;
if(!viewValue || !comparisonModel){
// It's valid because we have nothing to compare against
ctrl.$setValidity('lowerThan', true);
}
// It's valid if model is lower than the model we're comparing against
ctrl.$setValidity('lowerThan', viewValue <= comparisonModel );
return viewValue;
};
ctrl.$parsers.unshift(validate);
ctrl.$formatters.push(validate);
$attrs.$observe('lowerThan', function(comparisonModel){
return validate(ctrl.$viewValue);
});
};
return {
require: 'ngModel',
link: link
};
}
]);
朋克: http ://plnkr.co/edit/Fyqmg2AlQLciAiQn1gxY
我可以满足于在每个字段旁边都没有它,只要对其他字段集所做的更改确实触发了错误消息,在这种情况下,我可以将其弹出到顶部。 我看到的主要问题是,因为它们是数组codes[]
,它们最终传递到表单,所以它们将无法正常工作。
表单验证时已正确禁用了“提交”按钮,因此我不确定为什么消息仅锁定到添加的最后一行。
使用子窗体来分隔范围。
<ng-form name="frmChild">
<input name='codes' ng-model="bonus.code" lower-than="{{bonus.end_code}}" />
<input name='end_codes' ng-model="bonus.end_code" />
<span class="text-error" ng-show="frmChild.codes.$error.lowerThan">
Code must be less than End Code.
</span>
</ng-form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.