【问题标题】:using ng-repeat to populate table rows with data from array使用 ng-repeat 用数组中的数据填充表格行
【发布时间】:2016-03-25 19:36:35
【问题描述】:

我有一个名为 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-repeat 填充表。

<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

【问题讨论】:

  • 通常建议不要迭代函数的结果,而是使用函数分配范围变量,然后对其进行迭代。
  • 好的,我试试看
  • 如果错误没有解决,您可以发布错误吗?

标签: javascript angularjs


【解决方案1】:

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

有解释:

https://github.com/angular/angular.js/issues/705angular Infinite $digest Loop in ng-repeat

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

Infinite loop when ng-repeat/ng-class calls a function which calls $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">

【讨论】:

    【解决方案2】:

    简答 不要在 ngRepeat 上调用函数来返回项目。将项目数组存储在范围内的属性上。

    $scope.user_history = current_item.get_user_history();

    如果您确实需要这样做,您可以使用以下方法之一进行修复:

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

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

    长答案 查看this post 以获得有关其工作原理的非常好的解释。

    【讨论】:

      【解决方案3】:

      问题是摘要循环返回了一个承诺,而我不得不将它变成一个对象。

      我最初是这样做的:

      my_api.get_user_history(self.id);
      

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-19
        • 2023-03-25
        • 2018-12-16
        • 2018-04-12
        • 2014-06-18
        • 1970-01-01
        • 1970-01-01
        • 2017-01-21
        相关资源
        最近更新 更多