【问题标题】:How to display API which is in JSON to a View, using AngularJS?如何使用 AngularJS 将 JSON 格式的 API 显示到视图中?
【发布时间】:2016-08-25 00:01:27
【问题描述】:

我创建了一个从 URL 调用的 API,并在点击 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"
    }
  ]
}

我正在尝试使用工作正常的控制台日志访问 polls[0].options[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>

【问题讨论】:

    标签: angularjs json


    【解决方案1】:

    我会尝试以下方法,因为使用 ng-repeat 您可以遍历数组的所有项目,因此您不必使用索引:

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

    【讨论】:

    • 这仍然迭代对象中的键/值对,而不是数组。您将需要不同的迭代 ((k, v) in poll) 并以不同方式访问内部
    • @casraf 它是一个自 $scope.poll = response.polls 以来的数组,因此它等于 [{"total_votes": 2,"options": [ {"votes": "2","id": "2"}]
    【解决方案2】:

    这样用

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

    【讨论】:

    • 我没注意,但你写的不正确:poll 在范围内而不是整个对象,options 是一个数组
    猜你喜欢
    • 2015-03-01
    • 1970-01-01
    • 2016-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    • 2019-08-24
    • 2012-09-23
    相关资源
    最近更新 更多