功能描述:分页,点击按钮或者下一页获取分页接口,同时active到对应页码。
html模块:
<page page-count="totalPage" on-click-page="reloadData(page)"></page>
controller模块:
var context = $scope;
#scope.reloadData = reloadData;//(重要:需要与页面的事件进行绑定)
function reloadData(page) {
context.params.pageNumber = page || 1;//将参数变为点击的page,默认为1
getPackageList(context.params);//请求后端分页接口(根据业务todo)
}
directive模块:
(function () {//自定义指令
appModule.directive('page', pageController);
function pageController() {
return {
restrict: 'AE',
templateUrl: '/directive/page.html',
scope: {
pageCount:'=',//对应totalPage
onClickPage:'&' //对应reloadData()
}, link: function( scope, elem, attrs, c){
var context = scope;
context.onClickPrev = onClickPrev;
context.onClickNext = onClickNext;
context.onClickPageNumber = onClickPageNumber;
//$scope.watch为了兼容以前版本写法(如一开始就用这个分页组件,分页逻辑相同,可修改为下面一种写法)
!function init() { //!function init()效果和下面一样(这里做了老版本兼容)
context.pageNumber = 1;
scope.$watch(function () {
return context.pageCount//监听发现分页总数变了,执行后面函数
}, function () {
if (typeof context.pageCount != 'object' && typeof parseInt(context.pageCount) == 'number') {
var temp = [];
for (var i = 1; i <= context.pageCount; i++) {
temp.push(i);
}
context.pageCount = temp;
}
});
}();
//分页逻辑相同,可直接将init写为这样(不用兼容以前)
init();
function init(){
context.pageNumber = 1;
}
function onClickPageNumber(pageNumber) {
context.onClickPage({page:pageNumber});//这里必须按着这种格式写,他是根据数组中的参数名对应来找
//如果直接这样传参context.onClickPage(pageNumber),会报Cannot use 'in' operator to search for 'reloadData' in 2(寻找不到参数错误)
context.pageNumber = pageNumber;
context.showPrev = pageNumber > 1;
} function onClickPrev() {
context.pageNumber -= 1;
context.onClickPage({message:context.pageNumber});
if (context.pageNumber == 1) {
context.showPrev = false;
}
context.showNext = true;
} function onClickNext() { if (context.pageNumber < context.pageCount.length) {
context.pageNumber += 1;
}
context.onClickPage({message:context.pageNumber});
}
}
};
}
})();
directive模板:
<div class="page-holder" ng-show="pageCount.length>1">
<span class="prev m-link" ng-if="pageNumber != 1" ng-click="onClickPrev()"><</span>
<div style="display: inline" class="m-default"
ng-repeat="page in pageCount track by $index" ng-show="($index+1>pageCount.length-5&&pageNumber>pageCount.length-3)||($index<5&&pageNumber<4)||($index+1>pageNumber-3 && $index+1<pageNumber+3)">
<span class="page m-link" ng-class="{'green':page == pageNumber}"
ng-click="onClickPageNumber(page)">{{page}}</span>
</div>
<span class="next m-link" ng-if="pageNumber != pageCount.length" ng-click="onClickNext()">></span>
<span class="total-page m-default">共 {{pageCount.length}} 页</span>
</span>
</div> <style>
.page-holder {
display: inline-block;
height: 30px;
line-height: 30px;
margin-right: 20px;
float: right;
} .page, .prev, .next, .total-page {
color: #616161;
padding: 0px 6px;
border:1px solid #f2f2f2;
} .green{
color:#0A9908;
}
</style> 效果如下:
-----原创文章,©版权所有,转载请注明标明出处:http://www.cnblogs.com/doinbean