Creating forms dynamically using ng-repeat
and adding them to the vm.forms
object is causing issues. When an item is removed from the array, the corresponding form is deleted but the key in the vm.forms
object remains, leading to undefined
errors.
angular
.module('myApp', [])
.controller('FormLooper', FormLooper);
function FormLooper() {
var vm = this;
vm.children = [{
name: 'Sarah',
age: 9,
}, {
name: 'John',
age: 13,
}];
vm.removeChild = removeChild;
vm.forms = {};
vm.showSummary = false;
vm.triggerError = triggerError;
function triggerError() {
console.log('Available forms:', vm.forms);
console.log('property names:', Object.getOwnPropertyNames(vm.forms));
Object.getOwnPropertyNames(vm.forms).map(function(key) {
console.log('key', key, vm.forms[key]);
return vm.forms[key].$valid; // This will result in an `undefined` error
});
}
function removeChild(index) {
vm.children.splice(index, 1);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="FormLooper as vm">
<div ng-repeat="child in vm.children">
<form name="vm.forms.formId{{ $index }}">
<label>
Name: <input ng-model="child.name">
</label>
<br>
<label>
Age: <input type="number" ng-model="child.age">
</label>
</form>
<button ng-click="vm.removeChild($index)">RemoveChild</button>
</div>
<button ng-click="vm.triggerError()">Trigger Error (check your console output)</button>
</div>
</body>
View the code on JSFiddle for reference: http://jsfiddle.net/Tobbe/8eohL2nq/2/
It seems that Angular doesn't delete the entire object property automatically. One solution could be manually using delete
in the removeChild
function, but it's not ideal. Another option is to check for undefined
in the map function, which feels like a workaround. Is there a better way to handle this?
Any insights on how Angular handles adding and removing objects from vm.forms
would be appreciated.
UPDATE:
Note that even though Angular populates the vm.forms
object when forms are created, it doesn't remove entries when forms are deleted. Is this behavior intentional or a bug?