1

I am just blowing my mind. I can't understand how the code below is working.

I have a factory and inside an attribute called "products" and other called "order". Two methods, one called "list()" that returns the "products" attribute, and other called "orderList()" that returns "order". Also, it has a method called "add()" that get a "product" coming from the "products" list and populate the "order" list inside the factory. After that, I have two controllers and two lists. One controller for the products available ("products" attribute) and other for the shopping cart ("order" attribute).

At the beginning of each controller, I have $scope.productsList = Product.list(), and in the other one $scope.productsOrder = Product.orderList().

The products begins with the products list. The order begins empty. That's perfect.

When I click in the +1, those two changes to the "order" list. And have no idea why.

Here is the code: http://codepen.io/anon/pen/lFLbH

1 Answer 1

5

I believe you are asking why the amount changes in both the product list and in the cart. If so, my answer is for you. It is basic JavaScript- You are referencing the same object in memory so it updates in both views. To avoid this, you can make a copy of the object before adding it to the cart.

Change the line where you add the object to your cart to make a copy of the object.

 order[product.slug] = angular.copy(newProduct);
Sign up to request clarification or add additional context in comments.

1 Comment

Man, thank you very much! I can't believe that it was under my nose! =)

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.