0

I have this code in angular

$scope.b = {text: "b"};
$scope.a = {};
$scope.a = $scope.b;
$scope.a.text = "a";
console.log($scope.b); // Object {text: "a"};

It should be print Object {text: "b"}. I don't want 2 variables link together (when I change a, b should not change)

2
  • 1
    If you don't want $scope.a = $scope.b; then why do you have that line? Commented Jul 8, 2015 at 3:35
  • Because I need copy all value from b -> a. Commented Jul 8, 2015 at 3:36

2 Answers 2

2

in JavaScript, assign an object means ref to the object.

if you want make a and b refer to different objects. you should copy that.

angular provides two shortcuts for copy:

deep copy angular.copy

$scope.a = {};
//angular.copy(source, destination)
angular.copy($scope.b, $scope.a);

shallow copy angular.extend

$scope.a = {};
//angular.extend(destination, source1, source2 ...)
angular.extend($scope.a, $scope.b);
Sign up to request clarification or add additional context in comments.

Comments

0

Your code the same:

$scope.a = $scope.b = {};
$scope.a.text = "a" // $scope.a = $scope.b = {text: "a"}

Because $scope.a and scope.b have pointer to one Object, so when you change $scope.a the $scope.b will change.

Solution: you can use angular.copy(source, [destination]); You can read this link

angular.copy($scope.a, $scope.b);

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.