0

Why does http://plnkr.co/edit/sjmRT8XOCYPW3ntEnN3N?p=preview work and http://plnkr.co/edit/Tkizktj0kx3OQmAkSH6U?p=preview not.

The only difference is the like in Cart.js cartContent.push(product); VS cartContent = [{name: "Keyboard"}];

The only difference that I can see is the Angular object ( after being created has a ) $$hashKey key...

I want to completely over write the object cartContent and have it still available to cartBoxCtrl and productListCtrl

1 Answer 1

2

It is because in the second case you are overwriting the cartContent which is set as a reference to $scope.cart so any changes made to the cart is not reflected in the scope when you overwrite the content, since the $scope.cart still points to the old reference. So in your controller set the $scope.cart to Cart service and access cartContent in ng-repeat, so that the scope.cart now has the reference to the Cart object itself and any changes made to its property will be reflected in the scope's property as well.

controller('cartBoxCtrl', function ($scope, Cart){
    $scope.cart = Cart; //<-- here 
});

and

 <li ng-repeat="product in cart.cartContent track by $index">

Also note the usage of track by (here i have used $index, instead you could use a unique property on the object ex:- product.id) so that list will be tracked by that instead of the angular created unique key $$haskkey

Plnkr

or if you want to cleanup cartContent and still keep the cartContent as reference in your $scope.cart then you can do:-

this.addProduct = function (product) {
    //Cleanup the current array and insert new item
    this.cartContent.splice(0, this.cartContent.length, product);

};

Plnkr

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

3 Comments

The second part of your answer is exactly what i needed :) thanks !
@michaelcurry oh explanation wasn't required? :P
Oh, it was :P It made me explain what I was doing. Thanks you. [Been learning Angular from scratch for the past 2 days]

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.