我希望在单击“添加到购物车”按钮时,项目将添加到“我的购物车”中。这是我的 angularJS 代码
app.controller("OnlineShopping", function($scope)
{
$scope.items = [
{Product:"Moto G2", Desc: "Android Phone", Price: 10999},
{Product:"The Monk who sold his ferrari", Desc: "Motivational book", Price: 250},
{Product:"Mi Power Bank", Desc: "Power Bank", Price: 999},
{Product:"Dell Inspiron 3537", Desc: "Laptop", Price: 45600}
];
$scope.editing = false;
$scope.addItem = function(item) {
$scope.items.push(item);
$scope.item = {};
};
我在这里发现了一些关于使用 ng-model
和 ng-bing
的问题,但它适用于文本框,但在这里我没有从文本框中获取输入。这是我的“我的购物车”的不完整代码
<h2>My Cart</h2>
<div style="border: 1px solid blue;">
</div>
<table border="1" class="mytable">
<tr>
<td>Item</td>
<td>Description</td>
<td>Price</td>
</tr>
<tr ng-repeat="item in items">
<!-- What should be here -->
</tr>
</table>
最佳答案
您只需使用 .但在此之前,当您单击“添加到购物车”按钮时,需要将该项目添加到不同的变量 $scope.myCartItems
$scope.addToCart = function(item)
{
$scope.myCartItems.push(item);
}
模板会像下面这样变化,
<h2>My Cart</h2>
<div style="border: 1px solid blue;">
</div>
<table border="1" class="mytable">
<tr>
<td>Item</td>
<td>Description</td>
<td>Price</td>
</tr>
<tr ng-repeat="item in myCartItems">
<td>{{item.Product}}</td>
<td>{{item.Desc}}</td>
<td>{{item.Price}}</td>
</tr>
</table>
看看这个 plnkr。 http://plnkr.co/edit/zW7k8J9it1NIJE3hEwWI?p=preview
关于javascript - 如何在angularJS列表中添加项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30201305/