angularJS分页功能的简单实现
[ 2017/08/25, AngularJS , 4281阅, 0评 ]
思路:触发页码切换时发送对应请求到服务器,成功后替换原来的数据。适合PC端使用。
无限滚动加载:angularJS插件:ngInfiniteScroll无限滚动加载数据(自动分页)

1、controller

myApp.controller("pageNaviCtrl",['$scope','$http','pageNavi',function($scope,$http,pageNavi){
	$scope.pageCur = 1;
	$scope.pageAll = 0;
	$scope.pages = [];
	$scope.showPageNavi = false;
	$scope.loadPage = function(page){
		$http.get("http://yourdomain.com/aaa.php?pageNum="+page).success(function(res){
			//无数据时,不显示分页
			if(res.data.list.length>0){
				$scope.showPageNavi = true;
			};
			$scope.myList = res.data.list;
			$scope.pageCur = page;
			//从接口返回的数据中拿到总页数
			$scope.pageAll = res.data.totalPage;
			//调用分页算法服务取得要显示的页码数组
			$scope.pages = pageNavi.showLength($scope.pageCur,$scope.pageAll,5);
		}).error(function(){
			console.log("sth error...")
		});
	};
	//初始加载第一页
	$scope.loadPage($scope.pageCur);
}]);

2、service

/*分页算法服务*/
myApp.service('pageNavi',[function(){
	/**
	 * length 总页数
	 * current 当前分页
	 * displayLength 显示长度
	 * @return  array[1,2,3,4,5,6,7,8]
	 */
	this.showLength = function(current,length,displayLength){
		var indexes = [];  
		var start = Math.round(current - displayLength / 2);  
		var end = Math.round(current + displayLength / 2);  
		if (start <= 1) {  
			start = 1;  
			end = start + displayLength - 1;  
			if (end >= length - 1) {  
				end = length - 1;  
			}  
		}  
		if (end >= length - 1) {  
			end = length ;  
			start = end - displayLength + 1;  
			if (start <= 1) {  
				start = 1;  
			}  
		}  
		for (var i = start; i <= end; i++) {  
			indexes.push(i);  
		}  
		return indexes;
	}
}])

3、template

<dl ng-repeat="x in myList">
    <!--
    ...............
    -->
</dl>
<div class="navi" ng-if="showPageNavi">
    <a ng-if="pageCur!=1" ng-click="loadPage(1)">{{'首页'|L}}</a>
    <a ng-if="pageCur!=1" ng-click="loadPage(pageCur-1)">{{'上一页'|L}}</a>
    <a ng-repeat="p in pages" ng-class="{true:'current'}[pageCur==p]" ng-click="loadPage(p)">{{p}}</a>
    <a ng-if="pageCur!=pageAll" ng-click="loadPage(pageCur+1)">{{'下一页'|L}}</a>
    <a ng-if="pageCur!=pageAll" ng-click="loadPage(pageAll)">{{'尾页'|L}}</a>
</div>

原文:Angularjs实现分页和分页算法

有朋自远方来...评论一下呗O(∩_∩)O