2016-06-27 4 views
0

나는 사용자가 서로 다른 가격 인 크기 (개인, 중간 크기)를 기준으로 바구니에 식품 항목을 추가 할 수있는 응용 프로그램을 작성하고 있습니다. 내가 직면하고있는 문제는 두 개 이상의 항목을 추가 할 때 (배열을 사용하여) 배열의 모든 항목에 대한 가격이 변경된다는 것입니다. 나는 그 주위에 내 머리를 얻을 수 없다!각도 js 배열에 변경 값을 밀어 넣으십시오

사용자가 제품 (예 : 피자)을 선택하면 변수 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 

I 번째 항목을 추가 (크기 = 3) 내 배열 어레이

0: Object 
    extra: Object 
     price: "6.5" 
     size: "Large" 
     sizeInt: 3 
1: Object 
    extra: Object 
     price: "6.5" 
     size: "Large" 
     sizeInt: 3 

답변

5

상기 제 1 및 제 2 항목을 모두 변경 그것은 $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 
     } 
    }); 
}; 

또는 당신은 $scope.selectedProduct를 복사 할 수 있습니다 addToCartangular.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); 
}; 
+0

너무 고마워, 나는 그것을 알아낼 수 없었다! 당신은 내 문제를 해결했습니다 :) –

+0

@ JakeBown 도움을 기쁘게 –

0

불필요하게 selectedProduct$scope에 바인딩하는 것 같습니다.

$scope.selectedProduct을 지속적으로 업데이트하여 누를 수 있습니다. 동일한 참조를 반복해서 전달하기 때문에이 결과를 확인하십시오.

이 시도 : $scope.selectedProduct = {} : 당신의 addCart 기능에서

$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); 
}; 
0

당신은 selectedProduct이 방법을 재 선언한다. 이유 - 자바 스크립트에있는 객체가 참조에 의해 지정되며 모든 배열 요소에 동일한 객체가 있습니다. 따라서 여분을 변경할 때 참조로 각 항목을 업데이트하고 있습니다.

관련 문제