Angular js推动更改数组中的值

Jak*_*own 0 javascript jquery angularjs

我正在构建一个应用程序,允许用户根据不同价格的大小(个体,中等大小)将食物添加到篮子中.我面临的问题是,当我添加多个(使用ng-click)时,数组中所有项目的价格也会发生变化.我无法理解它!

当用户选择产品(例如披萨)时,变量selectedProduct将更改为所选产品.

这是我添加到购物篮中的代码:

$scope.addToCart = function(key, size, price) {


        //Add selected size and price

        //Add 'extra' for selected price and size
        $scope.selectedProduct.extra = {};
        $scope.selectedProduct.extra = {
            //price is a float
            price: price,
            //$scope.productSizes is a single array that
            //changes int values to sizes (1 => individual, 2 => medium ...)
            size: $scope.productSizes[size],
            //size is the int value of the size
            sizeInt: size
        };

        $scope.cart.push($scope.selectedProduct);
};
Run Code Online (Sandbox Code Playgroud)

当我通过push将一个项目(size = 1)添加到数组时,我在控制台中的额外键中得到它

0 Object
    extra: Object
      price: "1.99"
      size: "Individual"
      sizeInt: 1
Run Code Online (Sandbox Code Playgroud)

当我添加第二个项目(size = 3)时,我的数组会更改数组中的第一个和第二个项目

0: Object
    extra: Object
      price: "6.5"
      size: "Large"
      sizeInt: 3
1: Object
    extra: Object
      price: "6.5"
      size: "Large"
      sizeInt: 3
Run Code Online (Sandbox Code Playgroud)

Ser*_*ney 6

它正在发生,因为你正在推动对$scope.selectedProduct数组的引用.

参考文献的简短示例:

var a = {'key': 'foo'};
var b = a;
b['key'] = 'bar';
console.log(a['key']);   // initially it was 'foo'
Run Code Online (Sandbox Code Playgroud)

我建议你创建一个新对象addToCart并将其推入数组:

$scope.addToCart = function(key, size, price) {
    $scope.cart.push({
        extra: {
            price: price,
            size: $scope.productSizes[size],
            sizeInt: size
        }
    });
};
Run Code Online (Sandbox Code Playgroud)

或者你也可以复制$scope.selectedProductaddToCartangular.copy() :

$scope.addToCart = function(key, size, price) {
    var product = angular.copy($scope.selectedProduct);
    product.extra = {
        price: price,
        size: $scope.productSizes[size],
        sizeInt: size
    };
    $scope.cart.push(product);
};
Run Code Online (Sandbox Code Playgroud)