我正在构建一个购物车,我正在使用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>
答案 0 :(得分:1)
您可以尝试传递项目,而不是仅将数量添加为 addToBag 函数的参数:
<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);
};