使用ng repeat用数组中的数据填充表行

using ng-repeat to populate table rows with data from array

本文关键字:数据 填充 ng repeat 数组 使用      更新时间:2023-09-26

我有一个名为current_item.get_user_history()的JS函数,它通过调用API返回一个数组,看起来像这样:

things[0]:
 thing_id: 5
 user_id: 23
 paddle_no: 1234
 item_id: 893
 price: 5000
things[1]:
 thing_id: 4
 user_id: 67
 paddle_no: 6743
 item_id: 893
 price: 4500
... and so on

我希望能够从这个数组中获取数据,使用ng重复来填充表。

<div class="bid_history">
      <table>
        <tr>
          <th>
            Column 1
          </th>
          <th>
            Column 2
          </th>
          <th>
            Column 3
          </th>
        </tr>
        <tr ng-repeat="thing in current_item.get_user_history() track by thing.id">
        {{thing.user_id}} {{thing.price}}
        </tr>
      </table>
  </div>

出于某种原因,没有任何东西被渲染,而且它似乎重复了很多,因为我在chrome控制台中遇到了数量不可阻挡的错误。如有任何帮助,请准确解释如何使用ng-repeat

不能在ng-repeat中使用触发$digest()(如$http$timeout)的函数。它导致无限的$digest()循环。

有以下解释:

https://github.com/angular/angular.js/issues/705或ng重复中的有角度的无限$digest循环。

我以前也犯过同样的错误:)

ng repeat/ng类调用调用$http 的函数时的无限循环

您必须先保存current_item.get_user_history()数据,然后使用ng-repeat调用数据。

scope.things= urrent_item.get_user_history();
<tr ng-repeat="thing in things track by thing.id">

简短回答不要为退货项目调用ngRepeat上的函数。将项数组存储在作用域中的属性上。

$scope.user_history = current_item.get_user_history();

如果事实上你真的需要这样做,你可以用以下方法之一来修复它:

  1. 不要在每次调用current_item.get_user_history()时都创建新对象
  2. 如果需要创建新对象,可以为它们添加hashKey方法。有关示例,请参阅本主题

中等回答您通常不希望在ng repeat中对函数进行迭代。原因是current_item.get_user_history()返回了一个带有新对象的数组。此对象没有hashKey,也不存在于ngRepeat缓存中。因此,每个watch.get上的ngRepeat为其生成新的范围,并为{{thing.id}}生成新的监视。这只表在第一个watch.get()上有watch.last == initWatchVal。那么CCD_ 22。因此$digest开始新的遍历。然后ngRepeat用一块新手表创建一个新的范围,以此类推。然后在10次遍历后,你会得到一个错误。

长答案查看这篇文章,了解它的工作原理。

问题是摘要循环返回了一个promise,而我不得不将其转换为一个对象。

我最初是这样做的:

my_api.get_user_history(self.id);

并且必须将此添加到该行:

.then(function(data){self.user_history = data});

问题的一部分也是@Ealon提到的。我还决定将它存储在一个局部变量中,而不是返回函数的结果。我发布这个答案是因为上面的每个答案都是有效的,我需要考虑并组合起来解决我的问题。感谢大家的帮助和指导。