Hello, I am currently working on setting up an eCommerce shop using Angular. Below is the code snippet I am using:
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 created a factory that fetches product JSON after an AJAX request. I use ng-repeat as "product in products" to display all products in my HTML and have implemented a shopping cart where added products are displayed using ng-repeat of "cartProduct in cartProducts.itemlist track by $index". Each product has attributes like color, size, weight, etc. When an attribute is selected, its value (e.g., weight) and unit (e.g., kg) are stored in global variables activeAttrValue and activeAttrUnit. When 'add to cart' is clicked, these values are stored in cartProducts.
Problem: When multiple attributes of the same product are selected and added to the cart, only the last added product and attributes are being included. This results in an error message in the console:
Error: [ngRepeat:dupes] http://errors.angularjs.org/1.2.16/ngRepeat/dupes?p0=cartProduct%20in%20cartProducts.itemlist&p1=object%3A006
Upon logging $scope.cartProducts.itemlist in the console, I noticed that the attributes of both products are showing the same values.
I hope this explanation clarifies the issue at hand.