Reputation: 1297
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
Upvotes: 0
Views: 75
Reputation: 123739
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
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);
};
Upvotes: 2