【问题标题】:AngularJS - Displaying data from APIAngularJS - 显示来自 API 的数据
【发布时间】:2017-06-10 18:03:15
【问题描述】:

我是 AngularJS 的新手,在显示来自 api 调用的数据时遇到问题。

我想显示标题,但在某些时候卡住了。有人可以帮我循环一下吗?

这是我的index.html

controller.js

var app = angular.module('myApp', []);
app.controller('appController', function($scope) {
    //console.log("test");
        var url = "https://api.nytimes.com/svc/topstories/v2/home.json";
        url += '?' + $.param({
          'api-key': "853fc084776f46e29732e71b3f1269ae"
        });
        $.ajax({
          url: url,
          method: 'GET',
        }).done(function(result) {
          console.log(result);
          $scope.results = result;
        }).fail(function(err) {
          throw err;
        });
});

这是我的json

【问题讨论】:

  • 请发布您的 json 数据,以便我知道如何循环数据
  • json:在此处输入图像描述 -> 当您单击上面的链接时,它就在此处
  • 赞成答案兄弟:我需要声誉:)

标签: javascript angularjs json api loops


【解决方案1】:

您面临两个问题,第一个是在 angular 有自己的 http 服务时在 angular 中使用 jquery,您使用了 jquery ajax,因此结果变量在控制台中的 html 上将不可用,但您可以' t 在 html 中访问,所以我们必须像下面这样写。

$scope.$apply(function(){
        $scope.results = result.results;
});

现在循环看看下面的代码

<div ng-app="myApp" ng-controller="appController">
  <ul>
   <li ng-repeat="x in results">
     {{x.title}}
   <li>
  </ul>
</div>

工作codepen link

【讨论】:

    【解决方案2】:

    您提供的 JSON 是一个对象数组,而对象数组又包含一个带有标题的对象数组。
    因此,您需要一个如下所示的嵌套数组来显示 JSON 响应中的所有标题。

    <div ng-repeat="result in results">
      <div ng-repeat="child in result.results">
        {{child.title}}
      </div>
    </div>
    

    【讨论】:

      猜你喜欢
      • 2017-07-15
      • 2015-05-28
      • 2017-07-03
      • 1970-01-01
      • 2020-08-28
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 2022-12-23
      相关资源
      最近更新 更多