angular-infinite-scroll

作者 Zhs 日期 2016-05-27
angular-infinite-scroll

Angular的无限滚动实现-ngInfiniteScroll

前言

​ 手头项目打算用angular来实现,在预估项目难度的时候想到这个问题。于是查阅资料,找到这个插件。测试后可以满足需求,遂记录在此。

步骤

  1. 引入infinitscroll的js文件(依赖jquery)

    <script type='text/javascript' src='path/to/jquery.min.js'></script>
    <script type='text/javascript' src='path/to/angular.min.js'></script>
    <script type='text/javascript' src='path/to/ng-infinite-scroll.min.js'></script>
  2. 在模块上添加依赖

    angular.module('myApplication', ['infinite-scroll','other...']);
  3. 在需要无限滚动的html容器上添加infinite-scroll属性

    <div infinite-scroll="myPagingFunction()" infinite-scroll-distance="3"></div>
  4. 控制器中定义myPagingFunction() 函数,进行相应操作。

    完整代码

    <div ng-app='myApp' ng-controller='DemoController'>
    <div infinite-scroll='reddit.nextPage()' infinite-scroll-disabled='reddit.busy' infinite-scroll-distance='1'>
    <div ng-repeat='item in reddit.items'>
    <span class='score'>{{item.score}}</span>
    <span class='title'>
    <a ng-href='{{item.url}}' target='_blank'>{{item.title}}</a>
    </span>
    <small>by {{item.author}} -
    <a ng-href='http://reddit.com{{item.permalink}}' target='_blank'>{{item.num_comments}} comments</a>
    </small>
    <div style='clear: both;'></div>
    </div>
    <div ng-show='reddit.busy'>Loading data...</div>
    </div>
    </div>
var myApp = angular.module('myApp', ['infinite-scroll']);

myApp.controller('DemoController', function($scope, Reddit) {
$scope.reddit = new Reddit();
});

// Reddit constructor function to encapsulate HTTP and pagination logic
myApp.factory('Reddit', function($http) {
var Reddit = function() {
this.items = [];
this.busy = false;
this.after = '';
};

Reddit.prototype.nextPage = function() {
if (this.busy) return;
this.busy = true;
var url = "https://api.reddit.com/hot?after=" + this.after + "&jsonp=JSON_CALLBACK";
$http.jsonp(url).success(function(data) {
var items = data.data.children;
for (var i = 0; i < items.length; i++) {
this.items.push(items[i].data);
}
this.after = "t3_" + this.items[this.items.length - 1].id;
this.busy = false;
}.bind(this));
};
return Reddit;
});

以上来源于ngInfiniteScroll