I have the follow HTML:
<div ng-repeat="contact in vm.contacts">
<input type="text" ng-model="contact.firstName">
<input type="text" ng-model="contact.lastName">
<button ng-click="vm.addNew()">add</button>
</div>
and the following code on my Angular controller:
vm.contacts = [];
vm.addNew = addNew;
init();
function init() {
addNew();
}
function addNew() {
vm.contacts.push({});
}
So, when the page is started, the controller adds an empty object to the vm.contacts array.
My problem is: once I fill the fields and click on the add button, instead of creating an array entry with an empty object, angular is duplicating the previuous array entry.
So, if I enter "John" for first name and "Smith" for last name, and then click on the add button, the resulting array will be:
[
{firstName: "John", lastName: "Smith"},
{firstName: "John", lastName: "Smith"}
]
And the same contact will be displayed twice.
How do I prevent this from happening?
I've tried both to use track by $index on the ng-repeat declaration, and angular.copy() on the addNew function, and nothing seems to work. I want to be able to add a new empty contact, I do not wish to replicate or duplicate one.
Thanks in advance!