0

I have an ng-repeat that is cycling through $scope.myarray.

I have the following function:

var copy = $scope.myarray;

$.each(copy, function(index, data){
    data.name = "";
});

When I do this, it seems to be affecting my ng-repeat loop on $scope.myarray.

When I do:

console.log(copy);
console.log($scope.myarray);

They both seem to have the $$hashKey so I am thinking that is what is screwing things up.

What is the best way to manipulate my copy of the array without affecting the first version?

bryan
  • 8,879
  • 18
  • 83
  • 166
  • Why are you iterating over the array? Can you get away with making a copy with `angular.copy` and manipulating it separately? – Alexander Nied Oct 19 '16 at 19:12
  • I'm doing conditional checks on each item in the array, just didn't show it in my example @anied – bryan Oct 19 '16 at 19:13
  • Your code doesn't show conditional checks, it shows you making changes on items in the array... – Alexander Nied Oct 19 '16 at 19:14
  • Like I said, I'm just not showing it in my example. It had nothing to do with my question. `angular.copy` did not bring the $$hashkey over, thank you. – bryan Oct 19 '16 at 19:15

2 Answers2

1

to copy you should use

var copy = angular.copy($scope.myarray);
Vikash Kumar
  • 1,712
  • 1
  • 11
  • 17
0

By doing this:

var copy = $scope.myarray;

You are not creating a copy of $scope.myarray but you are just assigning the reference to $scope.myarray to a new variable.

so doing:

$.each(copy, function(index, data){
    data.name = "";
});

is exactly the same as

$.each($scope.myarray, function(index, data){
    data.name = "";
});

You need to copy all the items of the $scope.myarray to a new array (see this answer)

Depending on what kind of data you have in $scope.myarray, you might have to do a deep copy/cloning

Community
  • 1
  • 1
Alexis Cramatte
  • 408
  • 3
  • 6