如何将 ng-repeat 项添加到数组

How to add ng-repeat item to an array

我正在构建一个购物车,我正在使用 ng-repeat 遍历 JSON 对象列表。我创建了一个函数 addToBag,我想将该对象推入一个空数组,我将使用它在我的购物车结帐页面上显示项目。我无法访问自变量。

app.controller('shoppingController', function($scope, NgTableParams){
            var self = this;
            $scope.shoppingCart = [];
            $scope.shoppingItemCount = 0;
            $scope.total = 0;
            $scope.addToBag = function(quantity){
            quantity = parseInt(quantity);
            $scope.shoppingItemCount = $scope.shoppingItemCount + quantity;
                $scope.shoppingCart.push(self.item);
                console.log($scope.shoppingCart);

            };
});

 <tr ng-repeat="item in $data" ng-model="item.data">
   <form>
      <td title="'Search By Category'" filter="{ categories: 'text'}" sortable="'categories'">
        <img ng-src="{{item.imageUrl}}">
      </td>

      <td title="'Search by Name'" filter="{ name: 'text'}" sortable="'name'">
        <ul>
          <li><h1> {{item.name}}</h1></li>
          <li ng-model="price"><strong>Price:</strong> {{item.price | nfcurrency }}</li>
          <li><strong>Caffeine Scale:</strong>  {{item.caffeineScale}}</li>
          <li><strong>Rating:</strong> {{item.rating}}</li>
          <li><strong>In Stock?:</strong>      {{item.inStock | true_false}}</li>
          <li><strong>Categories:</strong>
            <ul ng-repeat="category in item.categories">
              <li>{{category}}</li>
            </ul>
          </li>
        </ul>

      </td>

      <td title="'Sort By Price'"sortable="'price'">
       <ul>
         <li>Quantity:
          <select class="form-control" ng-model="quantity">
            <option>1</option>
            <option>2</option>
            <option>3</option>
            <option>4</option>
            <option>5</option>
          </select>
          <input class="btn btn-success addbag" type="submit" ng-click="addToBag(quantity)"
           value="Add To Bag">
      </ul>

    </td>


</form>
  </tr>

除了为 addToBag 函数只添加数量作为参数外,您还可以尝试传递 item

 <input class="btn btn-success addbag" type="submit" ng-click="addToBag(quantity,item)"
       value="Add To Bag">

而函数 $scope.addToBag 就像:

$scope.addToBag = function(quantity, newItem){
        quantity = parseInt(quantity);
        $scope.shoppingItemCount = $scope.shoppingItemCount + quantity;
        $scope.shoppingCart.push(newItem);
        console.log($scope.shoppingCart);
};