【问题标题】:How to add item in list in angularJS?如何在angularJS的列表中添加项目?
【发布时间】:2018-10-12 19:41:19
【问题描述】:

我希望在单击“添加到购物车”按钮时,项目将添加到“我的购物车”中。这是我的 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-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>

【问题讨论】:

  • 您是否希望我们完成您的代码..或者您有一些疑问?
  • @pankajparkar 我只是想知道我哪里出错了。检查卡西尔的答案
  • 我期待您更新您的问题..bdw 很高兴看到您的问题得到解决

标签: javascript jquery html angularjs


【解决方案1】:

您只需要使用 . 添加单元格值。但在此之前,当您单击“添加到购物车”按钮时,需要将项目添加到不同的变量 $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); 后工作正常。如果您能解释一下它的作用,这对我和其他人也会更有帮助?
  • console.log 语句仅用于调试目的,它们对方法的功能没有任何影响。
【解决方案2】:

看起来不错。

尝试删除线

$scope.item = {};

并将其包裹在 $watch 周围

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-03
    • 1970-01-01
    • 1970-01-01
    • 2018-09-06
    • 2013-01-09
    • 1970-01-01
    • 2022-10-25
    • 2019-11-26
    相关资源
    最近更新 更多