使用Angular JS搜索NYT API

时间:2014-07-27 20:15:31

标签: javascript angularjs api

我在Angular JS中编写代码实现了一个标准的应用程序,它会在屏幕上显示搜索字段和搜索按钮,当运行搜索时,它应该拉入远程结果并在屏幕上显示它们 控制台没有向我显示任何错误,但我无法在屏幕上显示结果。我想知道如何在屏幕上显示结果

这是我的js文件中的代码

angular.module('plunker', [])
.controller('MainCtrl', ['$scope', '$http',
    function($scope, $http) {

      var clearError = function(result) {
        $scope.error = "";
        return result;
      };

      var applyData = function(result) {
        $scope.articles = result.data;
        console.log(result.data);
      };

      var rejected = function(error) {
        $scope.error = error.message;
      };

      var getArticles = function() {
        var url = "http://api.nytimes.com/svc/search/v2/articlesearch.json?q=North+Korea&api-key=052861d142cf4eb7fa12bb79781fdbe1:11:69591426";
        var promise = $http({
          method: 'GET',
          // https://jsonp.nodejitsu.com
          url: "https://jsonp.nodejitsu.com/?url=" + encodeURIComponent(url)
        });

        promise.success(clearError).then(applyData);
        promise.error(function(error) {
          $scope.error = error.message;
        });
      };
      getArticles();

      $scope.getRepos = _.debounce(getArticles, 300);

    }]);

这是html代码

<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="lodash.js@*" data-semver="2.4.1" src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>
  <script data-require="angular.js@1.2.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js" data-semver="1.2.17"></script>
  <script src="script.js"></script>
</head>

<body ng-controller="MainCtrl">
  <input ng-keyup="getArticles()" />
  <table>
    <thead>
      <tr>
        <td>Headline</td>
        <td>Body</td>
      </tr>
    </thead>
    <tbody>
      <tr ng-bind="error" style="color:red;"></tr>
      <tr ng-repeat="a in Articles">
        <td>{{a.headline}}</td>
        <td>{{a.body}}</td>
      </tr>
    </tbody>
  </table>
</body>

</html>

1 个答案:

答案 0 :(得分:0)

你有几个问题。

在范围内,您有articles,但在html中为Articles

要访问您想要的实际数据,您需要深入了解返回的数据对象:

尝试更改:

var applyData = function(result) {
    $scope.articles = result.data;
    console.log(result.data);
  };

要:

 var applyData = function(result) {
    var articles=result.data.response.docs
    $scope.articles = articles;
    console.log(articles);
  };

然后在html中,您需要稍微不同的属性,因为headline具有mainprint_headline

等子属性

例如

  <tr ng-repeat="a in articles">
    <td>{{a.headline.main}}</td>
    <td>{{a.lead_paragraph}}</td>
  </tr>

DEMO