Reputation: 97
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
?
Upvotes: 0
Views: 64
Reputation: 725
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
So when you edit an object, you're actually editing the original object
.
The solution
object = angular.copy(myObject1)
object = $.extend({}, myObject1);
Upvotes: 1
Reputation: 378
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
})
});
Upvotes: 1
Reputation: 3573
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);
Upvotes: 2
Reputation: 409
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);
Upvotes: 3