[英]Angular js push changing values in array
我正在構建一個應用程序,該應用程序允許用戶根據不同價格的尺寸(單個,中號)將食品添加到購物籃中。 我面臨的問題是,當我添加多個(使用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);
};
當我通過推將一個項目(大小= 1)添加到數組中時,會在控制台內的額外鍵中得到它
0 Object
extra: Object
price: "1.99"
size: "Individual"
sizeInt: 1
當我添加第二個項目(大小= 3)時,我的數組同時更改了數組中的第一項和第二項
0: Object
extra: Object
price: "6.5"
size: "Large"
sizeInt: 3
1: Object
extra: Object
price: "6.5"
size: "Large"
sizeInt: 3
發生這種情況是因為您將對$scope.selectedProduct
引用推入了數組。
參考的簡短示例:
var a = {'key': 'foo'}; var b = a; b['key'] = 'bar'; console.log(a['key']); // initially it was 'foo'
我建議您在addToCart
上創建一個新對象並將其推入數組:
$scope.addToCart = function(key, size, price) {
$scope.cart.push({
extra: {
price: price,
size: $scope.productSizes[size],
sizeInt: size
}
});
};
或者,您可以使用angular.copy()在addToCart
上復制$scope.selectedProduct
:
$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);
};
我認為您不必要地將selectedProduct
綁定到$scope
。
您不斷更新$scope.selectedProduct
並將其推入數組; 並看到此結果,因為您不斷傳遞相同的參考。
嘗試這個:
$scope.addToCart = function(key, size, price) {
//Add selected size and price
//Add 'extra' for selected price and size
var selectedProduct = {}; // new reference each time function is called
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(selectedProduct);
};
在addCart函數中,您應該這樣重新聲明selectedProduct: $scope.selectedProduct = {}
。 原因-javascript中的對象由引用分配,並且您在所有數組元素中都有相同的對象。 因此,當您進行其他更改時,您將通過引用更新每個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.