I'm facing an issue with modifying items from an array and adding them to a new list of objects.
The problem arises when I make changes to the item in the new list, it also reflects those changes in the original array. It seems like there is some reference linking the new and original items together.
To replicate this problem, please refer to the Controller's comments and run the code as "Full page":
angular.module('app', [])
.controller('MainCtrl', function($scope){
$scope.items = [
{id: 1, name: 'item 1'},
{id: 2, name: 'item 2'},
{id: 3, name: 'item 3'}
];
$scope.newItems = {
"hello": "World!"
};
//Function to add selected item object to $scope.newItems
$scope.addItem = function(item){
$scope.newItems.item = item;
};
//Add color property to the previously added object
$scope.addColor = function(clr){
$scope.newItems.item.color = clr;
};
//Although no changes are made to $scope.items, modifications to objects in the new list reflect on the original object.
//For testing purposes
$scope.$watch('items', function(newValue, oldValue){
if (newValue !== oldValue) {
$scope.showProblem = true; //this should NEVER occur
}
}, true);
});
<link data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="12707d7d66616660736252213c213c27">[email protected]</a>" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="24454a43514845564e5764150a100a1d">[email protected]</a>" data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.min.js"></script>
<body ng-app="app">
<div ng-controller="MainCtrl">
<div class="alert alert-danger" ng-if="showProblem">
<strong>UNDESIRED BEHAVIOR:</strong> Original items array has been modified.
</div>
<ul class="list-group">
<li ng-repeat="item in items track by item.id" class="list-group-item">
{{item.name}}
<a ng-click="addItem(item)" class="badge btn btn-sm btn-success" ng-if="!newItems.item">Add item</a>
<a ng-click="addColor('red')" class="badge btn btn-sm btn-success" ng-if="newItems.item.id === item.id">Add color property</a>
</li>
</ul>
<div class="panel panel-default">
<div class="panel-body">
<h3>Original item array</h3>
<pre>{{items | json}}</pre>
</div>
</div>
<div class="panel panel-default">
<div class="panel-body">
<h3>New item list</h3>
<pre>{{newItems | json}}</pre>
</div>
</div>
</div>
</body>