i am trying to make a eCommerce shop with angular and code is as follow
var shopApp = angular.module('shopApp', ["slugifier"], function() {});
controllers.productController = function($scope,FetchFactory) {
$scope.fetchProducts = function(offset) {
FetchFactory.items.fetchItems(offset).then(function(data){
$scope.products = data;
});
}
var activeAttrValue = 0;
var activeAttrUnit = 0;
var activeAttrId = 0;
$scope.add_to_cart() = function(index){
var newProd = [];
newProd = $scope.products[index]; // $scope.products have products json
newProd.quantity = 1;
newProd.attr_id = activeAttrId;
newProd.attr_value = activeAttrValue;
newProd.attr_unit = activeAttrUnit;
$scope.cartProducts.itemlist.push(newProd);
$scope.cartProducts.total_items++;
$scope.cartProducts.total_price += parseInt(newProd.price);
}
}
shopApp.controller(controllers);
i have a made a factory which will return me products json after a ajax request and using ng-repeat as "product in products" i am displaying all the products in my html and i have make a shopping cart where the products that are added to cart are being displayed by ng-repeat of "cartProduct in cartProducts.itemlist track by $index" products have attributes like color,size,weight etc. whenever a attribute is clicked its value(like weight) and unit(kg) are store in a global variables activeAttrValue,activeAttrUnit and if add to cart is clicked they are stored in cartProducts.
Problem: In case of multiple attributes. when one attribute is selected added to cart, and again another attribute of same product is selected and added to cart.ideally they should add to cart as two products but instead last added product and attributes only adds and in console gives a error
Error: [ngRepeat:dupes] http://errors.angularjs.org/1.2.16/ngRepeat/dupes?p0=cartProduct%20in%20cartProducts.itemlist&p1=object%3A006
when i tried console.log($scope.cartProducts.itemlist); i got this
Object
$$hashKey: "005"
attr_id: "3"
attr_unit: ""
attr_value: "blue"
,
Object
$$hashKey: "005"
attr_id: "3"
attr_unit: ""
attr_value: "blue"
attributes of both products changed to same
I hope i am clear with my problem.
ngRepeat:dupes
– PSL Oct 3 at 15:41newProd = angular.clone($scope.products[index]);
In the previous answer posted has information on why you might be seeing this issue. angular.clone should remove$$hashKey
. Anyways if it same item being pushed into the cart why dont you associate a counter for item, instead of pushing the same object. – PSL Oct 3 at 15:45angular.clone
. Did you check my comment earlier? – PSL Oct 3 at 15:54