2

I do not know why when I assign 1 scope to another like this:

$scope.test1 = "hello";
$scope.test1 = $scope.test2;

Sometimes if I change $scope.test2, $scope.test1 changes too, and sometimes not. And also sometimes if I change $scope.test1, $scope.test2 changes too.

Why is this happening? maybe I am in a promise or something like that?

I do not need a solution I just want the theory of this, angular.copy is the solution.

Here is my code:

$scope.topicsQuery.should = $scope.appliedOrFilters;
$scope.appliedOrFilters.splice(i, 1); 
$scope.topicsQuery.should.splice(filtersToDelete[i],1);

Then if appliedOrFilters changes topicsQuery.should will change too and if topicsQuery.should changes appliedOrFilters will change too.

But if i put this:

$scope.topicsQuery.should = [];

nothing changes.

Does .splice change the property of an object?

vict
  • 212
  • 1
  • 3
  • 14

1 Answers1

3

Original answer

From Javascript by reference vs. by value

  • Javascript is always pass by value, but when a variable refers to an object (including arrays), the "value" is a reference to the object.

  • Changing the value of a variable never changes the underlying primitive or object, it just points the variable to a new primitive or object.

  • However, changing a property of an object referenced by a variable does change the underlying object.

So, if you change the object reference it won't be updated.

$scope.test1 = "hello";
$scope.test2 = $scope.test1;
$scope.test1 = "world";

console.log($scope.test2); //prints "hello"

But if you change the property of an object, it will be updated:

$scope.test1 = {"title": "hello"};
$scope.test2 = $scope.test1;
$scope.test1.title = "world";

console.log($scope.test2.title); //prints "world"

-

For the Updated Question

$scope.topicsQuery.should = $scope.appliedOrFilters;

All modification to the array .should or .appliedOrFilters will be saw on the 2 variables.

$scope.appliedOrFilters.splice(i, 1);
$scope.topicsQuery.should.splice(filtersToDelete[i],1);

As seen in the documentation , splice edits the array itself, so it's good.

$scope.topicsQuery.should = [];

Here you create a new array and assign it to .should.

So the .appliedOrFilters still points to the previous array, perfectly normal.

If you want to erase the array, you just should do

$scope.topicsQuery.should.splice(0, $scope.topicsQuery.should.length);
Community
  • 1
  • 1
Francescu
  • 16,974
  • 6
  • 49
  • 60