2016-08-24 24 views
0

我有一個創建的API,我從URL調用,並在打到API時得到響應。這是我的控制器。如何使用AngularJS將JSON中的API顯示到視圖中?

adminApp.controller('PollController', function($scope,$window,$timeout, $routeParams, $http, $location) { 
     var story_id = 1; 
      $http({ 
      method: 'get', 
      url: ""+story_id, 
      }). 
      success(function(response) { 
      // console.log(response); 
      //displayMessage('Sent','200px'); 
      $scope.poll = response.polls; 
      console.log("======================"); 
      console.log(response.polls); 
      console.log("======================"); 
      console.log(response.polls[0].options[0].votes); 
      }). 
      error(function(response) { 
       console.log(response || "Request failed"); 
      }); 



}); 

而當我點擊API時,我得到以下內容。

{ 
    "num_polls": 1, 
    "polls": [ 
    { 
     "total_votes": 2, 
     "options": [ 
     { 
      "votes": "2", 
      "id": "2" 
     } 
     ], 
     "id": "3" 
    } 
    ] 
} 

我試圖進入投票站[0]可供選項[0] .vote使用控制檯日誌,工作正常,但我怎麼使用AngularJS視圖顯示呢?

我試過但沒有工作。那麼如何從API訪問詳細信息?

<tr ng-repeat="tableDetail in poll"> 
<td ng-bind="tableDetail.polls[0].options[0].votes"></td> 
<td ng-bind="tableDetail.id "></td> 
</tr> 

回答

0

我會嘗試以下方法,因爲與ng-repeat您遍歷數組的AVER的項目,所以你不必使用索引:

<tr ng-repeat="tableDetail in poll"> 
    <td>{{tableDetail.options[0].votes}}</td> 
    <td>{{tableDetail.id}}</td> 
</tr> 
+0

這仍然遍歷對象中的鍵/值對,而不是數組。你需要一個不同的迭代(poll中的'(k,v)),並以不同的方式訪問內部 – casraf

+0

@casraf它是一個數組,因爲'$ scope.poll = response.polls'因此它將等於'[{ 「total_votes」:2,「options」:[{「votes」:「2」,「id」:「2」}]'。 –

+0

你說得對,我的不好 – casraf

0

用這種方式

<tr ng-repeat="tableDetail in poll"> 
<td> 
{{tableDetail.polls.options.votes}} 
</td> 
<td> {{tableDetail.id}} </td> 
</tr> 
+0

我沒注意,但是你寫的是不正確的:'poll'在範圍內而不是整個對象,'options'是一個數組 –

相關問題