Vinas
Vinas

Reputation: 159

Angular array.push() creates a duplicate for ng-repeat

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!

Upvotes: 1

Views: 1658

Answers (2)

liamguy165
liamguy165

Reputation: 42

I think the problem arises here:

    <input type="text" ng-model="contact.firstName">
    <input type="text" ng-model="contact.lastName">

Once the array receives the first and last contact names, the input after that can only be the first and last name stored in contact as the first values are being stored in contact and from there on can only use those values.

Upvotes: 0

daan.desmedt
daan.desmedt

Reputation: 3820

Something like this:

VIEW

<div ng-app="app" ng-controller="MainController as vm">

  {{vm.contacts}}

  <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>

</div>

CONTROLLER

angular
  .module('app', [])
  .controller('MainController', MainController)


function MainController($timeout) {

  var vm = this;
  vm.contacts = [{}];

  vm.addNew = addNew;

  function addNew() {
      vm.contacts.push({});
  }    
}

JSFIDDLE

Upvotes: 2

Related Questions