cjmling
cjmling

Reputation: 7288

$scope object get updated too when updating local var variable

I have $scope.stock_filters object and i want to assign to a new variable something like this.

var new_data_object = $scope.stock_filters[$scope.key_filter];

Now when i update a key of this object like

new_data_object.name = 'blablabla';

Why does $scope.stock_filters[$scope.key_filter].name get updated too ?

What am I doing wrong ? How I can fix this ?

Upvotes: 0

Views: 29

Answers (1)

Michael Kang
Michael Kang

Reputation: 52867

You are modifying the instance by reference, which is why both references are being affected. If you just want to create a copy of an instance, you can use angular.copy:

 var new_data_object = angular.copy($scope.stock_filters[$scope.key_filter]);

 new_data_object.name = 'blablabla';

Upvotes: 1

Related Questions