在Angular.js中将ng-repeat转换为无限滚动

时间:2015-11-25 16:04:28

标签: javascript angularjs api http

目前在Angular中,我正在向JSON新闻源发送http请求。我在加载时使用data-ng-init =" init()"启动http请求。不过,我希望这个节目只有一篇文章,并且有一个无限卷轴。换句话说,一旦用户到达每篇文章的底部,我希望加载其他文章。

这是我当前的index.html

<section ng-app="sports" ng-controller="main" data-ng-init="init()">
    <div ng-repeat="article in articles | limitTo:2">
        <div class="col-lg-8 col-lg-offset-2 col-md-8 col-md-offset-2 col-sm-8 col-sm-offset-2">
            <!-- <h3>{{ article.created }}</h3> -->
            <h1>{{ article.title }}</h1>
            <img class="images afkl-lazy-image" src="{{ article.thumbnail }}">      
            <p ng-bind-html=" article.body | html "></p>
        </div>
    </div>
</section>

这是我的angularApp.js:

app.controller('main', function($scope, $http){
    $scope.init = function(){
        $http.get("/data")
        .success(function(response) {
            $scope.articles = [];
            $.each(response.node,function(index,item){
                $scope.articles.push(item);
            })
            $scope.articles.reverse();
        });
    }}
);

我会回答任何问题。提前谢谢!!

1 个答案:

答案 0 :(得分:0)

您只需要向页面添加一个滚动侦听器,捕获事件并加载更多数据,然后再加载#34;页面&#34;一次:

$scope.currentPage = 0;

$scope.loadPage = function(pageNum){

   $http.get("/data?page=" + pageNum)
      .success(function(response) {
          $scope.currentPage = pageNum;
          $.each(response.node,function(index,item){
              $scope.articles.push(item);
          })

      });
   }}
};

window.onscroll = function(ev) {
    if ((window.innerHeight + window.scrollY) >=     document.body.offsetHeight) {
       $scope.loadPage($scope.currentPage + 1);

    }
};

你应该真正注入$ window服务并使用它:

...controller('mycontroller', function($scope, $window) {
    angular.element($window).bind("scroll", function() {
       ///check to see if you're at the bottom and call method to load data as above
    });
});