AngularJS:实现页面滚动到底自动加载数据的功能
要实现这个功能,可以通过https://github.com/sroze/ngInfiniteScroll这个第三方控件来实现。步骤如下:
1. 下载ng-infinite-scroll.js程序http://sroze.github.io/ngInfiniteScroll/ 目前版本是1.0.0
2. 如果你是用的jQuery2.0以上版本,还需要修改ng-infinite-scroll.js程序,将所有的将所有的$window.xxx改为$(window).xxx, elem.xxx改为$(elem).xxx
3. 在HTML中引入script
<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>
4. HTML示例代码如下:
1 <div ng-controller='PostListController'> 2 <div infinite-scroll='demo.nextPage()' infinite-scroll-disabled='demo.busy' infinite-scroll-distance='1'> 3 <div ng-repeat='item in demo.items'> 4 <p> 5 <input type="hidden" value="{{item.PostId}}" /> 6 <label>{{item.WriterName}}</label> 7 <label>{{item.WriterMail}}</label> 8 <label>{{item.WreckerName}}</label> 9 <label>{{item.StartDate}}</label> 10 <label>{{item.Location}}</label> 11 <label>{{item.Story}}</label> 12 </p> 13 </div> 14 <div ng-show='demo.busy'>Loading data...</div> 15 </div> 16 </div>
5. PostListController.js代码如下:
1 var ftitAppModule = angular.module('ftitApp', ['infinite-scroll']); 2 3 ftitAppModule.controller('PostListController', 4 function ($scope, Demo) { 5 $scope.demo = new Demo(); 6 }); 7 8 // 创建后台数据交互工厂 9 ftitAppModule.factory('Demo', function ($http) { 10 var Demo = function () { 11 this.items = []; 12 this.busy = false; 13 this.after = ''; 14 this.page = 0; 15 }; 16 17 Demo.prototype.nextPage = function () { 18 if (this.busy) return; 19 this.busy = true; 20 21 var url = "http://192.168.3.95:7002/api/post/nextpage?id=" + this.page + "&callback=JSON_CALLBACK"; 22 $http.jsonp(url).success(function (data) { 23 var items = data; 24 for (var i = 0; i < items.length; i++) { 25 this.items.push(items[i]); 26 } 27 this.after = "t3_" + this.items[this.items.length - 1].id; 28 this.busy = false; 29 this.page += 1; 30 }.bind(this)); 31 }; 32 33 return Demo; 34 });
这样就实现了页面拖动到底后,从服务器自动加载数据的功能。