1

Kindly explain me this behavior. I have decalred 2 variables.

$scope.data = {'value' : 123};
    $scope.v1 = $scope.data;

Now if i change the value

$scope.data.value = 2;

and try to print

alert('old value is '+$scope.v1.value);

It gives me output as 2 whereas I think it should give me value as 123. Kindly tell me that is it the same behavior like Java where one variable has different instances and change in one reflects in another ?

1
  • 2
    It's a reference to the same object. Commented Dec 22, 2014 at 15:24

2 Answers 2

1

As you're guessing you are not creating a new object when you assign $scope.data to $scope.v1. You're just "pointing" $scope.v1 to $scope.data which implies that any change that you do to $scope.data will be reflected also in $scope.v1.

If you want to have different elements you should make a copy of the object. Look at angular.copy

Sign up to request clarification or add additional context in comments.

Comments

1

Yes. You want to use angular.copy() to solve your current issue.

Anyways this all happens because of making one Object equal to another is assigning a reference; not creating a copy.

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.