0

So I'm copying a $scope.property by defining it as the value of another variable var query, and when I update the value of var query it changes the value of $scope.property.

Why does this happen and how can I avoid this?

My code looks something like this:

var query = $scope.property;
if(condition) {
    console.log($scope.property);
    $.extend(query, anotherObj);
    console.log($scope.property);
}

The output in the console looks like this:

> Object {details-type: "order", details-bind_date_formatted: "03/19/2013"}
> Object {details-type: "order", details-bind_date_formatted: "03/19/2013", details-state: "CA"}

I've never encountered this problem in vanilla javascript.

Kevin Beal
  • 10,500
  • 12
  • 66
  • 92

2 Answers2

2

Why does this happen

You noticed that query === $scope.property? The both refer to the exact same object, which you alter between the two log statements.

and how can I avoid this?

How do you want to avoid this? Do you expect query to be a clone of the object? Then see How do I correctly clone a JavaScript object? or What is the most efficient way to deep clone an object in JavaScript? for that.

I've never encountered this problem in vanilla javascript.

Unlikely, since jQuery is only built of vanilla JS:

var scope = {a:{b:1}};
var a = scope.a;
console.log(scope.a); // or just log(a);
a.c = 0; // or scope.a.c = 0;
console.log(scope.a); // or just log(a);
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
2
var query = angular.copy($scope.property);
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
user2251745
  • 178
  • 1
  • 2
  • 10