1

I don't really understand why this piece of code works the way it does.

I call my service and get the expected data returned. I wish to store the pictures seperately, as I need to modify the array and parse it differently to new scopes. The thing I don't understand is, that as I now have created 2 scopes, product and productPictures - why are these still linked?

If I use Lodash to _.sort() productPictures, then the Images object inside scope.Product will also be altered, however I do not want this happen, and I don't know how to isolate the $scope.productPictures. I tried handling the scopes as simple js variables such as var product; and var productPictures, but as I set their data according to the response from the service, they are still linked.

$api.productpage.query({
    id: parseInt($stateParams.productId)
}, function (data) {
    $scope.product = data[0];

    $scope.productPictures = data[0]['Images'];
});

Am I overlooking something super trivial? Should I rather manage the product images in a seperate service request?

2 Answers 2

5

Objects are passed by reference in javascript. It means that in this code

$scope.product = data[0];
$scope.productPictures = data[0]['Images'];

$scope.productPictures points to the same object (I guess this is array in your case) as data[0].Images.

To overcome this issue you need to clone object instead of just reference. You might want to check angular.copy method:

$scope.productPictures = angular.copy(data[0].Images);
Sign up to request clarification or add additional context in comments.

1 Comment

I cannot tell you how much I appreciate your extremely fast answer. Everything works wonders now. Thank you so much!
-1

You create two variables in the scope not two scope.

Object are passed by reference so if you modify one it modidy the other. Maybe try to clone the object

edit use angular.copy() instead of jquery.extend()

function myclone ( obj){
   return jQuery.extend(true, {}, obj);  
}

2 Comments

OP asked about angular, why do you use a jQuery function?
angularjs use jquery lite. didn't know the angular.copy() function thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.