gpt4 book ai didi

javascript - 在 Angular js中使用推送功能

转载 作者:行者123 更新时间:2023-11-30 08:41:16 25 4
gpt4 key购买 nike

我正在尝试用angular创建一个电子商务商店,代码如下

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);

我有一个工厂,它将在 ajax 请求后返回我的产品 json 并使用 ng-repeat 作为“产品中的产品”我在我的 html 中显示所有产品,我制作了一个购物车,其中的产品被添加到购物车正在由“cartProducts.itemlist track by $index 中的 cartProduct”的 ng-repeat 显示产品具有颜色、尺寸、重量等属性。每当单击属性时,其值(如重量)和单位(kg)存储在全局变量 activeAttrValue、activeAttrUnit 中,如果单击添加到购物车,它们将存储在 cartProducts 中。

问题:在多个属性的情况下。当选择一个属性添加到购物车时,再次选择同一产品的另一个属性并将其添加到购物车。理想情况下,它们应该作为两个产品添加到购物车,但最后添加的产品和属性只添加并且在控制台中给出错误

 Error: [ngRepeat:dupes] http://errors.angularjs.org/1.2.16/ngRepeat/dupes?p0=cartProduct%20in%20cartProducts.itemlist&p1=object%3A006

当我尝试 console.log($scope.cartProducts.itemlist);我明白了

 Object
$$hashKey: "005"
attr_id: "3"
attr_unit: ""
attr_value: "blue"
,
Object
$$hashKey: "005"
attr_id: "3"
attr_unit: ""
attr_value: "blue"

两个产品的属性都变成了一样

我希望我清楚我的问题。

最佳答案

Angular 默认不允许在 ng-repeat 上重复元素。为了解决这个问题,您需要在 ng-repeat 指令中添加一个“track by”。

例如,对于具有重复元素的数字列表:

<div ng-repeat="value in [1, 1, 1, 2, 2] track by $index"></div>

有关更多信息,请查看 url of your error

关于javascript - 在 Angular js中使用推送功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26181089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com