Reputation: 14122
I have a variable form list and want to display validation error messages outside of the list elements.
consider this template:
<form name="gForm">
<table>
<tr ng-repeat="invoice in invoices" ng-form="invoiceForm">
<td><input name="amount" type="number" max="200" /></td>
</tr>
</table>
<div ng-show="gForm.invoiceForm.amount.$invalid">you must the money</div>
<button ng-click="addInvoice()">add invoice</button>
</form>
the validation error would only be displayed when the last ng-repeat is invalid. Put another way, gForm.invoiceForm
points to the lastly created form in ng-repeat.
I've seen other questions related to this problem but they only suggest repeating the validation messages inside the ng-repeat. I need the message to be outside and displayed once only.
Upvotes: 0
Views: 917
Reputation: 1995
Are you looking for something like this? Yes you need to use ng-model, but also you need a unique name:
<div ng-app="pageModule"
ng-controller="parentCtrl">
<form name="gForm">
<table>
<tr ng-repeat="invoice in invoices" ng-form="invoiceForm">
<td>{{invoice.name}}: <input name="invoice.name" required type="number" max="200" ng-model="invoice.amount" /></th>
</tr>
</table>
<div ng-show="gForm.$invalid && showError">you must the money</div>
<button ng-click="addInvoice()">add invoice</button>
</form>
</div>
<script>
var pageModule = angular.module('pageModule',[])
.controller('parentCtrl',function($scope) {
$scope.invoices = [
{ name : 'ford' },
{ name : 'chevy' },
{ name : 'honda' },
]
$scope.showError = false;
$scope.addInvoice = function() {
$scope.showError = true;
console.log('add invoice');
}
})
</script>
Upvotes: 1
Reputation: 48211
The way you have it, gForm.invoiceForm
does refer to the last <tr>
in ng-repeat.
If you want to display the error when any of the amounts is invalid, you can use gForm.$invalid
. In fact there is no need to use ng-form="invoiceForm"
unless there are more requirements not evident from the current question's code.
Another problem is that, in order for Angular to recognize the input and apply its directive (and its magic consequently), the ng-model
directive is required as well.
Adding the ng-model
directive and changing the condition to gForm.$invalid
solves the problem:
...
<tr ng-repeat="invoice in invoices">
<td><input name="amount" type="number" max="200"
ng-model="invoice.amount" /></td>
</tr>
...
<div ng-show="gForm.$invalid">you must the money</div>
...
See, also, this short demo.
Upvotes: 1