Search code examples
angularjsangularjs-scope

Why product quantity change, When i am push two or more than two time of same product in array


I am having the following problem when I am pushing same product two times in the array then both product quantity showing same. For Example Suppose ABC is my product when I push it into XYZ array with 10 quantity, second-time same product push in XYZ array with quantity 15 then both product quantity showing 15, means last push product quantity replace in all product which is the same name and same id. Here is my code which I have done, please check and rectify my issue.

JS Code

    $scope.XYZ = [];
    $scope.addProductInBag = function(prod){
    $scope.XYZ.push(prod); //inside of prod productname,quantity,id as well.
    }

HTML Code

<a class="btn btn-default" ng-click="addProductInBag(prod)">Push</a>
   <div ng-repeat="prd in XYZ">
     <div>{{prd.id}}</div>
     <div>{{prd.productname}}</div>
     <div>{{prd.quantity}}</div>
   </div>

Solution

  • The below code works fine. Please check this plunker for your given example scenario.

    Controller:

      $scope.XYZ = [];
      $scope.addProductInBag = function(prod){
        var dummy = {
          id: 10001 + ($scope.XYZ.length),
          productname: 'TEST' + ($scope.XYZ.length + 1),
          quantity: 2 + ($scope.XYZ.length)
        }
        $scope.XYZ.push(dummy);
      };