srikanta mondal
srikanta mondal

Reputation: 119

scope variable updated automatically when I am updating another scope variable

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.

Upvotes: 0

Views: 56

Answers (3)

Rami Farhat
Rami Farhat

Reputation: 1

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?

Upvotes: 0

oguzhan00
oguzhan00

Reputation: 509

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?

Upvotes: 3

Paarth
Paarth

Reputation: 10377

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();

Upvotes: 0

Related Questions