Javascript 如何在angularJS的列表中添加项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30201305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add item in list in angularJS?
提问by Sagar


I want that on click of "Add to Cart" button, item will add on "My Cart". Here is my angularJS code
我希望点击“添加到购物车”按钮,项目将添加到“我的购物车”中。这是我的 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 = {};
};
I found some questions here with using ng-modeland ng-bingbut it works with textbox, but here I am not taking input from the textbox. Here is my incomplete code for "My Cart"
我在这里发现了一些问题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>
回答by Kathir
You just need to add the cell values using the . But before that When you click on "Add to Cart" button the item needs to be added to a different variable $scope.myCartItems
您只需要使用 . 但在此之前,当您单击“添加到购物车”按钮时,该项目需要添加到不同的变量 $scope.myCartItems
$scope.addToCart = function(item)
{
$scope.myCartItems.push(item);
}
And the template will change like below,
模板会像下面一样改变,
<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>
Take a look at this plnkr. http://plnkr.co/edit/zW7k8J9it1NIJE3hEwWI?p=preview
看看这个plnkr。http://plnkr.co/edit/zW7k8J9it1NIJE3hEwWI?p=preview
回答by Sagar
It looks good.
这看起来不错的样子。
Try removing the line
尝试删除该行
$scope.item = {};
and also wrap it around a $watch
并将其包裹在 $watch 周围
$scope.$watch('items', function(){
console.log('items changed');
});

