Neeraj kaushik Neeraj kaushik - 3 months ago 13
AngularJS Question

Prevent change of object in original array when updating filtered object

I have an array

$scope.items = [{id:1 , name:'john'},{id:2, name:'doe'}];

Now i am filtering object from the array

$scope.newItem = $filter('filter')($scope.items, {id: 1})[0];

Then, i am using $scope.newItem in a update form But when i type in fields the object in original array ($scope.items) is also changing . Can Anyone Help What i am doing Wrong.

For more description ,

I am doing two steps. In first step i am fetching all the items and storing in $scope.items . then in second step , on click edit from the items list i am filtering object of that id here let 1 ,

$scope.newItem = $filter('filter')($scope.items, {id: 1})[0];

then after displaying the newitem i want to update it . and when i type something to update the fields in newitem the original object in the original array is also updating ...


You are messing object oriented concepts.

Actually using '=' would mean that changing a property of $scope.items would change the corresponding property of $scope.newItem or vice versa.

If you don't want to change original array use below changes,

$scope.items = [{id:1 , name:'john'},{id:2, name:'doe'}]; 

var copiedOne=angular.copy($scope.items);

Then Update your copied one

$scope.newItem = $filter('filter')(copiedOne, {id: 1})[0];

I hope this works for you.