您的位置:首页 > Web前端 > AngularJS

AngularJS 无限滚动加载数据控件 ngInfiniteScroll

2017-11-24 00:00 781 查看
1、什么是 InfiniteScroll?
无限滚动(Infinite Scroll)也称为自动分页、滚动分页和无限分页。常用在图片、文章或其它列表形式的网页中,用来在滚动网页到页面底部的时候自动加载下一页的内容。
这种形式最早由推特(twitter)使用,后来必应图片搜索、谷歌图片搜 索、google reader等纷纷采用了这一项技术,于是靠滚动浏览器滚动条来翻页的技术慢慢在互联网上遍站开花。该技术非常适合移动端的数据自动加载。

2、什么是ngInfiniteScroll?
ngInfiniteScroll 是用于 AngularJS的无限滚动控件,特点是简单易用,是AngularJS社区里应用最为广泛的”触底加载”控件。

3、如何使用ngInfiniteScroll
只要以下4步就可以搞定ngInfiniteScroll :

<1>引用javascript文件(注意把js加载顺序)

<script type='text/javascript' src='path/jquery.min.js'></script>
<script type='text/javascript' src='path/angular.min.js'></script>
<script type='text/javascript' src='path/ng-infinite-scroll.min.js'></script>

<2>声明对 ***infinite-scroll***的依赖

angular.module('myApplication', ['infinite-scroll']);


<3>在html页面使用 infinite-scroll 元素

<div infinite-scroll="myPagingFunction()" infinite-scroll-distance="3"></div>

<4>ok,调用你的分页函数 myPagingFunction(),开始使用吧。使用细节参考[ngInfiniteScroll API文档](http://sroze.github.io/ngInfiniteScroll/documentation.html)。下附例子:
[ngInfiniteScroll 动态加载实例](http://sroze.github.io/ngInfiniteScroll/demo_async.html)

HTML代码:

<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>

Javascript 代码(自动加载 Reddit):

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 = "http://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;
});

特别提醒:
容易犯的错误,把ng-repeat标签和infinite-scroll放在同一个

标签下:

<!-- 错误的写法! -->
<div infinite-scroll='pagerFunction()' ng-repeat='item in items'>
{{item}}
</div>

<!-- 正确的写法! -->
<div infinite-scroll='pagerFunction()'>
<div ng-repeat='item in items'>{{item}}</div>
</div>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  angularJS infinite