2016-08-24 58 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'是一个数组 –