0

I have two objects : $scope.objectA and $scope.objectB. I assign value from $scope.objectA to $scope.objectB like this:

$scope.objectB.value1 = $scope.objectA.value1;

then I make value1 of $scope.objectB to null;

$scope.objectB.value1 = null;

My question is why when I assign $scope.objectB.value1 to null, $scope.objectA.value1 is null too. How can I keep value of $scope.objectA.value1 while changing value of $scope.objectB.value1?

1
  • 1
    In your code you only use $scope.objectB Commented Jan 19, 2016 at 7:32

4 Answers 4

3

Make copy of object B and assign it to the object A. Use angular.copy function. It will creates a deep copy of source.

For more information Visit Angular copy doc

$scope.objectA.value1 = angular.copy($scope.objectB.value1);
Sign up to request clarification or add additional context in comments.

Comments

2

Because this is how it works. You make these two variables "bound" together. If you want to keep value of objectA, then use

$scope.objectB.value1 = angular.copy($scope.objectA.value1);

Comments

1

I think this can happen only if ObjectA and ObjectB refer to the same object on the heap, i.e. it ObjectA and ObjectB are the same objects

$scope['object1'] = {};
$scope['object1']['val'] = {};
$scope['object2'] = {};
$timeout(() => {
  this.$scope['object2']['val'] = this.$scope['object1']['val'];
  $timeout(() => {
   this.$scope['object2']['val'] = null;
      console.log(this.$scope['object1']['val']); // Object {}
    })
});

-

 $scope['object1'] = {};
    $scope['object1']['val'] = {};
    $scope['object2'] = {};
    $timeout(() => {
      this.$scope['object2']['val'] = this.$scope['object1']['val'];
      $timeout(() => {
       this.$scope['object2']['val'] = null;
          console.log(this.$scope['object1']['val']); // null
        })
    });

Comments

1

The reason is when you assign object to a variable, the assignment will be by reference, so the old and new will be a reference to the original object

enter image description here

So when you edit an object, you're actually editing the original object.

The solution

  1. Angular: use object = angular.copy(myObject1)
  2. jQuery: object = $.extend({}, myObject1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.