如何在Angular UI Bootstrap Pagination中生成链接

lyn*_*yle 10 javascript angularjs

我一直在继续学习角度,现在已成功使用角度ui bootstrap分页.我能够显示项目列表以及正确的页数.每当我点击分页时,也会切换到正确的页面.

现在我的问题是,如果用户想要为某个页面添加书签,或者为了确保用户在刷新浏览器时保持在同一页面上,我该如何处理它.浏览器的地址栏上没有生成链接(href).我还需要设置路线吗?请你发一些例子,因为它会对我有很大的帮助.谢谢.

Kha*_* TO 12

您需要设置路由,您可以使用routeProviderui路由器来完成

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

这里我用currentPageas参数设置一个路由:

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

在您的控制器中,您可以从$routeParam以下位置检索当前页面:

$scope.currentPage = $routeParams.currentPage || 1; //default to 1 if the parameter is missing
//load your paged data from server here.
Run Code Online (Sandbox Code Playgroud)

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

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

源代码

DEMO链接

通过路由,您还需要更新代码以从服务器加载分页数据.我们不会在currentPage更改时立即加载数据(在这种情况下是$ watch函数).我们在检索$routeParam.currentPage参数时加载分页数据.

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

app.config(function($routeProvider) {
  $routeProvider
    .when('/page/:currentPage?', {
        templateUrl: "template.html",
        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>");
}]);
Run Code Online (Sandbox Code Playgroud)

源代码

DEMO链接


小智 0

是的,如果您希望您的应用程序允许链接到某些状态,那么您必须让您的应用程序利用routeProvider。

官方文档没有大量有关路线的信息,但教程有此页面:

http://docs.angularjs.org/tutorial/step_07

约翰·林德奎斯特 (John Lindquist) 精彩的短视频教程也值得一看。处理路线的一种方法是:

http://www.egghead.io/video/gNtnxRzXj8s