2015-04-06 42 views
0

我試圖通過一個HTTP請求將一個對象綁定到一個表中的angularjs。如何將對象綁定到AngularJS中的表格?

這樣做的正常方法是使用ng-repeat,如下所示。

<table class="table table-striped"> 
     <tr> 
      <th>name</th> 
      <th>artist</th> 
     </tr> 
     <tr> 
      <td ng-repeat="track in $scope.trackList.items"> 
       {{ track.name }} 
       {{ track.artist }} 
      </td> 
     </tr> 
    </table> 

這樣做的問題是,頁面加載和NG-重複數據從服務器沒有造成項目是集合因此沒有被抽入表中返回之前跑了。

這樣做的最好方法是什麼?

回答

1

這裏不需要$ scope就是簡單的trackList.items。

$ scope是粘合劑b/w視圖和控制器,你不需要在視圖中顯式調用$ scope,它已經暗示事物已經從範圍中選取。

<td ng-repeat="track in trackList.items"> 
       {{ track.name }} 
       {{ track.artist }} 
      </td> 

如果你是那麼這裏談論的HTTP調用來的,將在視圖中反映,以及你不需要的雙向由$ HTTP調用結合到picture.If任何更新的控制器魔力手動完成。

希望它有幫助。 :)

+0

哈哈很好,它固有地工作!我正在深入研究它+錯字......謝謝! – Jamesla 2015-04-06 05:45:05

1

在您看來,您並不需要$scope。此外,你可能想要 <tr>,而不是<td>

<table class="table table-striped"> 
    <tr> 
     <th>name</th> 
     <th>artist</th> 
    </tr> 
    <tr ng-repeat="track in trackList.items"> 
     <td>{{ track.name }}</td> 
     <td>{{ track.artist }}</td>     
    </tr> 
</table> 
0

讓我糾正你的代碼首先

<table class="table table-striped"> 
    <tr> 
     <th>name</th> 
     <th>artist</th> 
    </tr> 
    <tr> 
     <td ng-repeat="track in trackList.items">{{ track.name }}</td> 
     <td>{{ track.artist }}</td> 
     </tr> 
</table> 

您不必明確指定$範圍,同時結合數據。

就您的問題而言,即使代碼在頁面加載完成時執行,您對範圍數據所做的任何更改都會被角度和視圖所尊重,並且會得到更新。

就你的情況而言,在頁面加載時,如果trackList.items中有數據可用,它將顯示在頁面中。否則,表格將只顯示標題。稍後,當應用程序從AJAX(或任何其他來源)接收數據時,您必須將其簡單地分配給您的JS代碼中的$scope.trackList。這將導致即時查看更新,您將看到表格開始反映新數據。