Jabaa Jabaa - 3 years ago 94
AngularJS Question

Angular js:ng-model is over writing the items in the ng-repeat

I have a strange problem with my ng-repeat array.

Currently, I am listing an array using

ng-repeat
and an edit button is placed to edit the particular item and save to the database.

But the problem is when the particular
item
in the text box is changed the
ng-repeat
items are also changed.

Here is the fiddle of my issue

https://plnkr.co/edit/D5NQitsRg7sCfZBE9IaB?p=preview

Change the value in textfield it will also affect the values in
ng-repeat

Answer Source

you are assigning the reference of the variable that's why its changing. you have to copy the variable. below is working example:-

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  
  $scope.items= [
       {id:1,name:'first'},{id:2,name:'second'}
    ];
    
    $scope.editItem = function(index){
    //edit
      $scope.edit = angular.copy($scope.items[index]);
      
    }
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
  
  <p ng-repeat="item in items">{{item.id+','+item.name}}
  
  <span ng-click="editItem($index)">Click to Edit {{item.name}} item</span>
  </p>
  
  
  <h2>Edit</h2>
   <input type="text" ng-model="edit.name" />
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download