angular+bootstrap分页指令案例

时间:2021-05-27 17:55:28

AngularJS中不仅内置了许多指令,而且开发人员也可以通过自定义指令来完成特殊操作,指令创建成功后可以到处复用。

Web应用中的分页处理最为常见,我们可以将分页模块编写成一个可以复用的Angular指令,在使用时无需考虑指令的内部实现细节,像使用普通HTML元素一样简单。

1:index.html

<!DOCTYPE html>

<html ng-app="myApp">
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../css/bootstrap.css"/>
</head>
<body> <div class="container" ng-controller="PageCtrl">
<pagination num-pages="pages" curr-page="page" on-select-page="selectPage(page)"></pagination>
</div> </body> <script src="../js/angular.js"></script>
<script src="index.js"></script>
</html>

分页指令的使用如下:

<pagination num-pages="pages" curr-page="page" on-select-page="selectPage(page)"></pagination>

index.js

var myApp = angular.module('myApp', []);

myApp.controller('PageCtrl',['$scope', function($scope){
$scope.pages = 10;
$scope.page = 1; $scope.selectPage = function(page){
console.log("选择的页:"+page);
};
}]); myApp.directive('pagination', function(){
return {
restrict: 'E',
scope: {
numPages: '=',
currPage: '=',
onSelectPage: '&'
}, template: '<ul class="pagination">'
+'<li ng-class="{disabled: noPreviousPage()}">'
+'<a ng-click="selectPreviousPage()">上一页</a>'
+'</li>' +'<li ng-repeat="page in pages" ng-class="{active: isActivePage(page)}">'
+'<a ng-click="selectPage(page)">{{page}}</a>'
+'</li>' +'<li ng-class="{disabled: noNextPage()}">'
+'<a ng-click="selectNextPage()">下一页</a>'
+'</li>' +'</ul>', replace: true,
link: function(s){
s.$watch('numPages', function(value){
s.pages = []; for(var i=1;i<=value;i++){
s.pages.push(i);
} if(s.currPage > value){
s.selectPage(value);
}
}); //判读是否有上一页
s.noPreviousPage = function(){
return s.currPage === 1;
}; //判断是否有下一页
s.noNextPage = function(){
return s.currPage === s.numPages;
}; //判断当前页是否被选中
s.isActivePage = function(page){
return s.currPage===page;
}; //选择页数
s.selectPage = function(page){
if(!s.isActivePage(page)){
s.currPage = page; s.onSelectPage({ page:page });
}
}; //选择下一页
s.selectNextPage = function(){
if(!s.noNextPage()){
s.selectPage(s.currPage+1);
}
}; //选择上一页
s.selectPreviousPage = function(){
if(!s.noPreviousPage()){
s.selectPage(s.currPage-1);
}
};
}
};
});

3:运行效果如下:

angular+bootstrap分页指令案例

angular+bootstrap分页指令案例