In my AngularJS app, I use ng-repeat to display rows of records. When the user removes the last record in the array, it removes the custom properties on the form tag. This is breaking all of the custom validations set to those properties. If the user removes all other records, the properties are still intact. Any help is much appreciated. Please see the plunker for code.
http://plnkr.co/edit/8s5brh7Hj9cu0gdpNpxt?p=preview
<body ng-controller="MainCtrl as vm">
<form name="vm.cptForm" role="form" ng-submit="vm.submit()" novalidate="">
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>DATE OF SERVICE</th>
<th>REMOVE</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in vm.items">
<td>{{item.id}}</td>
<td type = "text"
name="name"
class = "form-control ng-class: 'error': vm.showErrors && !vm.cptForm.name.$valid}"
ng-model="item.name">{{item.name}}</td>
<td type = "text"
name="dos"
class = "form-control ng-class: 'error': vm.showErrors && !vm.cptForm.dos.$valid}"
ng-model="item.dos">{{item.dos}}</td>
<td>
<button class="btn btn-xs btn-danger" type="button" ng-click="vm.remove(item)">Delete</button>
</td>
</tr>
</tbody>
</table>
<div class="row">
<span class="error" ng-show="vm.showErrors && vm.cptForm.dos.$error.termedMember">
</form>
</body>
and here's the js
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
var vm = this;
vm.cptForm = {};
vm.items = [];
vm.items = [
{
"id":0,
"name": "Jane",
"dos":"05/05/2017"
},
{
"id":1,
"name": "Janet",
"dos":"05/05/2017"
},
{
"id":2,
"name": "John",
"dos":"05/05/2017"
},
{
"id":3,
"name": "Johnathan",
"dos":"05/05/2017"
},
{
"id":4,
"name": "Joanne",
"dos":"05/05/2017"
}
];
vm.remove = function(item){
console.log(item);
console.log(vm.cptForm); //before splice vm.cptForm contains dos and name properties
var index = vm.items.indexOf(item);
debugger;
vm.items.splice(index,1);
// console.log(vm.items);
//console.log(vm.cptForm); //after splice vm.cptForm no longer contains dos and name properties
vm.validate(vm.items);
};
vm.validate = function(items){
angular.forEach(items,function(item){
if(item.dos < getDate()){ //compared to today for code simplicity
vm.cptForm.dos.$setValidity("termedMember", false);
}
});
};
});
Edit I tried creating a copy of the form prior to splicing it and then assigning it back to the original form, but that did not work. How can I retain the form's properties for each item when using ng-repeat?
<td>tag does not have a "type" attribute, andng-modelis really meant to be used with<input>tags (and other things that the user can actually enter data into). I'm surprised your code works as is, have you tried putting a<input type="text">with the ng-model/name attributes, inside the<td>? Also, when I delete the last item in your plunkr, it's not clear to me that a problem has occurred...