如何在AngularJS中向列表中添加项目?

6

快照

我希望点击“加入购物车”按钮后,商品将被添加到“我的购物车”中。以下是我的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-modelng-bind的问题,但它仅适用于文本框,而这里我没有从文本框中获取输入。下面是我的“我的购物车”不完整代码:

    <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>

你想让我们完成你的代码,还是你有一些疑问? - Pankaj Parkar
@pankajparkar,我只是想知道我错在哪里。请检查kathir的答案。 - Sagar
我以为你会更新你的问题...顺便说一句,很高兴看到你的问题已经解决了。 - Pankaj Parkar
2个回答

14

您只需使用.来添加单元格值。但在此之前,当您单击"添加到购物车"按钮时,需要将该项添加到另一个变量$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


在我的AngularJS代码中添加console.log("Adding to the cart"); console.log(item);后,它可以正常工作。如果您能解释一下它的作用,对我和其他人都会更有帮助。 - Sagar
console.log语句仅用于调试目的,它们对方法的功能没有任何影响。 - Kathir

0

看起来不错。

尝试移除这行。

$scope.item = {};

并且还要将它包裹在 $watch 中

$scope.$watch('items', function(){
      console.log('items changed');
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接