javascript – 如何在Angular UI Bootstrap分页中生成链接

我一直在继续学习角度,现在已经成功地使用了角度ui引导分页.我可以显示项目列表和正确的页数.并且每当我点击分页时也切换到正确的页面.

现在我的问题是如果用户想要为某个页面添加书签,或者确保用户在刷新浏览器时保持在同一页面上,那我该怎么做呢?在浏览器的地址栏上没有生成链接(href).我还需要设置路线吗?你能否发表一些例子,因为这将大大有助于我.谢谢.

解决方法

您需要设置路由,您可以使用 routeProviderui router

在这个例子中,我使用路由提供程序进行演示,但是想法是一样的.

在这里我设置一个以currentPage为参数的路由:

app.config(function($routeProvider) {
  $routeProvider
    .when('/page/:currentPage',{
        templateUrl: "template.html",controller: PaginationDemoCtrl
    })
});

在控制器中,您可以从$routeParam检索当前页面

$scope.currentPage = $routeParams.currentPage || 1; //default to 1 if the parameter is missing
//load your paged data from server here.

您可以只需$watch当前页面进行更改,并相应地更新相应的位置:

$scope.$watch("currentPage",function(value){
     if (value){
        $location.path("/page/" + value);
     }
  })

Source code

DEMO link

使用路由,您还需要更新代码以从服务器加载分页数据.当currentPage发生变化时(在这种情况下是$watch功能),我们不会立即加载数据.当我们检索$routeParam.currentPage参数时,我们加载我们的分页数据.

根据@Harry的要求,这里是通过覆盖引导html模板生成href链接的另一种解决方案:

app.config(function($routeProvider) {
  $routeProvider
    .when('/page/:currentPage?',controller: PaginationDemoCtrl
    })
})
.run(["$templateCache","$rootScope","$location",function($templateCache,$rootScope,$location) {

  $rootScope.createPagingLink = function(pageNumber){
    return "#" + $location.path().replace(/([0-9])+/,pageNumber);
//Here is a sample function to build href paths. In your real app,you may need to improve this to deal with more case.
  }

  $templateCache.put("template/pagination/pagination.html","<ul class=\"pagination\">\n" +
    "  <li ng-if=\"boundaryLinks\" ng-class=\"{disabled: noprevIoUs()}\"><a ng-href=\"{{$root.createPagingLink(1)}}\">{{getText('first')}}</a></li>\n" +
    "  <li ng-if=\"directionLinks\" ng-class=\"{disabled: noprevIoUs()}\"><a ng-href=\"{{$root.createPagingLink(page - 1)}}\">{{getText('prevIoUs')}}</a></li>\n" +
    "  <li ng-repeat=\"page in pages track by $index\" ng-class=\"{active: page.active}\"><a ng-href=\"{{$root.createPagingLink(page.number)}}\">{{page.text}}</a></li>\n" +
    "  <li ng-if=\"directionLinks\" ng-class=\"{disabled: noNext()}\"><a ng-href=\"{{$root.createPagingLink(page + 1)}}\">{{getText('next')}}</a></li>\n" +
    "  <li ng-if=\"boundaryLinks\" ng-class=\"{disabled: noNext()}\"><a ng-href=\"{{$root.createPagingLink(totalPages)}}\">{{getText('last')}}</a></li>\n" +
    "</ul>");
}]);

Source code

DEMO link

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...