2016-03-25 76 views
0

數據表中的行我有一個名爲current_item.get_user_history()返回一個陣列,通過製作和API調用JS功能,看起來沿此線的東西:採用NG-重複來用數組

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> 

出於某種原因沒有得到渲染,似乎做了很多重複的,因爲我得到的鉻控制檯錯誤的不可阻擋的數量。任何幫助表示讚賞,以解釋如何使用ng-repeat

+1

通常建議不要遍歷函數的結果,而是使用該函數分配給範圍變量,然後迭代該範圍變量。 –

+0

好的,我會試試 –

+0

如果它沒有解決,你能發佈錯誤嗎? – Thalaivar

回答

0

問題是,摘要循環正在返回一個承諾,我不得不把它變成一個對象。

我最初做這個:

my_api.get_user_history(self.id); 

,不得不把它添加到該行:問題的

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

部分也正是這一點@Ealon所提及。我還決定將它存儲在本地變量中,而不是返回函數的結果。我發佈了這個答案,因爲上面的每個答案都是我需要考慮併合起來解決問題的所有有效部分。謝謝大家的幫助和指導。

2

您不能在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"> 
0

簡答 不要叫上ngRepeat函數的返回項目。將項目數組存儲在範圍內的屬性上。

$scope.user_history = current_item.get_user_history();

事實上,如果你真的需要做到這一點,您可以通過以下方式之一來解決它:

  1. 不要在每次調用current_item.get_user_history()創建新的對象。
  2. 如果您需要創建新對象,則可以爲它們添加hashKey方法。例子見this topic

中回答 你一般不想遍歷以ng重複的功能。原因是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爲一個很好的解釋如何工作。