【问题标题】:How to fetch data from objects in angularjs?如何从angularjs中的对象中获取数据?
【发布时间】:2017-12-15 18:00:02
【问题描述】:

我正在做一个简单的购物车系统。

我创建了一个表格来显示每个产品侧面的添加到购物车按钮的产品。单击按钮时,我能够获取每个产品的索引,但无法获取对象内的数据(名称、价格和数量)。请帮忙!我怎样才能得到它们?谢谢。

< script >
  var app = angular.module("shoppingCart", []);
app.controller("cartCtrl", function($scope) {
  $scope.products = [{
      id: 1,
      name: 'Baby Mix Lobster (300g - down)',
      unit: 'per kg',
      price: 2500,
      qty: 1
    },
    {
      id: 2,
      name: 'Tiger Lobster (1kg - up)',
      unit: 'per kg',
      price: 5800,
      qty: 1
    },
    {
      id: 3,
      name: 'Tiger Lobster (700g - 999g)',
      unit: 'per kg',
      price: 4500,
      qty: 1
    },
    {
      id: 4,
      name: 'Tiger Lobster (500g-699g)',
      unit: 'per kg',
      price: 4200,
      qty: 1
    },
    {
      id: 5,
      name: 'Tiger Lobster (300g-499g)',
      unit: 'per kg',
      price: 3900,
      qty: 1
    },

  ];




  $scope.addToCart = function(item) {

    alert(item);

  }



});

<
/script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>




  <table style="border: 1px solid black">
    <tr>
      <th></th>
      <th>name</th>
      <th>unit</th>
      <th>price</th>
      <th>Qty</th>
      <th></th>
    </tr>
    <tr ng-repeat="x in products">
      <td>{{$index + 1}}</td>
      <td>{{x.name}}</td>
      <td>{{x.unit}}</td>
      <td>{{x.price | currency: "Php " : 2}}</td>
      <td><input type="number" min="1" placeholder="{{x.qty}}" /></td>
      <td><button ng-click="addToCart($index)">Add to Cart</button></td>

    </tr>
  </table>
</div>

【问题讨论】:

  • 你不会根据 id 号而不是任意增量索引添加到购物车吗?

标签: angularjs


【解决方案1】:

需要传递项目x而不是index

ng-click="addToCart(x)"

【讨论】:

  • 我试图使用索引来获取数据。呵呵。您的解决方案也很有效,非常感谢!
  • @Kkk 没问题。如果这有帮助,请务必检查作为答案
【解决方案2】:

如果你能得到索引,那为什么不从数组中取出对象呢?

$scope.addToCart = function(index) {
    var item = $scope.products[index];
    // access the properties of `item` here.
}

另外,建议追踪ng-repeat的项目:

ng-repeat="x in products track by $index"

【讨论】:

  • 不知道我必须把它放在一个变量中。我像这样直接获取它 $scope.addToCart = function(index) { $scope.products.name[item];非常感谢人!您的解决方案有效。我现在可以获取数据了。
猜你喜欢
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 2013-08-21
  • 2011-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多