0

I am getting ajax request data and assigning to one scope variable $scope.customerEvents = data; then I am using another variable to modify the data

    var datanew=data;
    datanew.unshift({'customer_events_id':   'ID','date':'Date','event':'Event','eventsubtype':'Event Subtype','eventtype':'Event Type','time':'Time','user_id':'User ID','user_mrn':'User MRN','user_name':'User Name','user_role':'User Role'});
    $scope.downloadcsv=datanew;

But customerEvents is getting updated.

srikanta mondal
  • 119
  • 2
  • 15

3 Answers3

3

you should use:

$scope.customerEvents = angular.copy(data);

Creates a deep copy of source, which should be an object or an array.

That's the documentation.

Also you can look at this question: Javascript equivalent of assign by reference?

Community
  • 1
  • 1
oguzhan00
  • 499
  • 8
  • 16
0

Sure, customerEvents and datanew are probably both referencing the same object (referenced by 'data'). Clone the array when you copy it to datanew and you'll be modifying only datanew and eventually $scope.downloadcsv and not customerEvents.

change var datanew=data; to var datanew=data.slice();

Paarth
  • 9,687
  • 4
  • 27
  • 36
0

you have to do a deep copy of your object unless it will be referenced by the first variable. you can use:

  • angular.copy(data)

  • angular.merge(dst, src) : documentation.

  • or you can use jquery.clone()

Also you can refer to this post : Deep copying objects in angular?

Community
  • 1
  • 1