使用ngInfiniteScroll从远程源输出JSON

时间:2015-09-17 18:40:46

标签: javascript html json ajax angularjs

我使用AngularJS 1.4创建了一个小应用程序,它从远程源输出JSON数据。

Here is the JSON data in question.

以下是我的观点 - ngInfiniteScroll的链接位于container的顶部:

<body ng-app="cn" ng-controller="MainCtrl as main">

  <div id="header" class="container-fluid">
    <p>Camper News</p>
  </div>

  <div class="container">
    <div infinite-scroll="feed.loadMore()" infinite-scroll-distance="3">
      <div ng-repeat="newsItem in myData" class="news-row col-sm-12 col-xs-12">
        <div class="col-sm-2 col-xs-12">
          <div id="img-container">
            <img ng-src={{newsItem.author.picture}} id="user-avatar" />
          </div>
        </div>
        <div class="news-text col-sm-10 col-xs-12">
          <a href={{newsItem.link}}><em>{{newsItem.headline}}</em></a>
        </div>
        <div class="col-sm-10 col-xs-12" id="link-description">
          {{newsItem.metaDescription}}
        </div>
        <div class="col-sm-12 col-xs-12" id="bottom-text">
          <div class="col-sm-4 col-xs-12" id="author">
            <a href='http://www.freecodecamp.com/{{newsItem.author.username}}'>{{newsItem.author.username}}</a>
          </div>
          <div class="col-sm-4 col-xs-12" id="likes">
            <i class="fa fa-thumbs-o-up"></i> {{newsItem.upVotes.length}}
          </div>
          <div class="col-sm-4 col-xs-12" id="timestamp">
            <span am-time-ago={{newsItem.timePosted}} | amFromUnix></span>
          </div>
        </div>
      </div>
    </div>
  </div>

</body>

我试图使用ngInfiniteScroll错开加载和输出数据。我只是不确定它是如何工作的:

app.controller('MainCtrl', function($scope, Feed) {
    $scope.feed = new Feed();
});

app.factory('Feed', function($http) {
    var Feed = function() {
        this.items = [];
        this.after = '';
    };

    Feed.prototype.loadMore = function() {
        var url = "http://www.freecodecamp.com/news/hot";
        $http.get(url).success(function(data) {
            var items = data;
            // Insert code to append to the view, as the user scrolls
        }.bind(this));
    };

    return Feed;
});

Here is a link to the program on Codepen.与ngInfiniteScroll(controllerfactory)相关的代码目前已被注释掉,以支持工作版本,但这当然会同时加载所有链接。

为了逐步加载JSON,我需要在factory中插入什么内容?

1 个答案:

答案 0 :(得分:1)

据我所知,通过查看FreeCodeCamps'story routes,无法查询“热门新闻”故事的具体范围。

它看起来只是以固定的100个故事限制返回json。

  function hotJSON(req, res, next) {
    var query = {
      order: 'timePosted DESC',
      limit: 1000
    };
    findStory(query).subscribe(
      function(stories) {
        var sliceVal = stories.length >= 100 ? 100 : stories.length;
        var data = stories.sort(sortByRank).slice(0, sliceVal);
        res.json(data);
      },
      next
    );
  }

您可以对其返回的故事使用无限滚动,以显示您在chunks as you scroll中从请求中检索的本地数据。