简体   繁体   English

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

[英]How to generate links in Angular UI Bootstrap Pagination

I have been continuing learning angular and have now used the angular ui bootstrap pagination successfully. 我一直在继续学习角度,现在已成功使用角度ui bootstrap分页。 I am able to display the list of items together with the correct number of pages. 我能够显示项目列表以及正确的页数。 And also switch to the correct page whenever I click on the pagination. 每当我点击分页时,也会切换到正确的页面。

Now my question is if a user wanted to bookmark a certain page, or to make sure the user stays on the same page whenever he refreshes the browser, how do I go about it. 现在我的问题是,如果用户想要为某个页面添加书签,或者为了确保用户在刷新浏览器时保持在同一页面上,我该如何处理它。 There are no links (href) being generated on the address bar of the browser. 浏览器的地址栏上没有生成链接(href)。 Do I also need to set routes? 我还需要设置路线吗? Can you please post some examples, as it would greatly help me. 请你发一些例子,因为它会对我有很大的帮助。 Thanks. 谢谢。

You need to set up routes, you can do it using routeProvider or ui router 您需要设置路由,您可以使用routeProviderui路由器来完成

In this example, I use route provider to demonstrate, but the idea is the same. 在这个例子中,我使用路由提供程序来演示,但想法是一样的。

Here I set up a route with currentPage as parameter: 这里我用currentPage作为参数设置一个路由:

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

In your controller, you can retrieve the current page from $routeParam : 在您的控制器中,您可以从$routeParam检索当前页面:

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

You could just $watch current page for changes and update the location accordingly: 你可以只看$watch当前页面进行更改并相应地更新位置:

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

Source code 源代码

DEMO link DEMO链接

With routing, you also need to update your code to load paged data from server. 通过路由,您还需要更新代码以从服务器加载分页数据。 We don't load data immediately when the currentPage changes (in this case is the $watch function). currentPage更改时,我们不会立即加载数据(在本例中是$ watch函数)。 We load our paged data when we retrieve the $routeParam.currentPage parameter. 我们在检索$routeParam.currentPage参数时加载分页数据。

As requested by @Harry, here is another solution to generate href links by overwriting bootstrap html template: 根据@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>");
}]);

Source code 源代码

DEMO link DEMO链接

We can do this with the $location, without needing $route. 我们可以使用$ location执行此操作,而无需$ route。

Here is an example of how to call the pagination from Angular UI Bootstrap: 以下是如何从Angular UI Bootstrap调用分页的示例:

<pagination ng-model="Controls.currentPage"
            total-items="Controls.totalItems"
            items-per-page="Controls.videosPerPage"
            max-size="5"
            rotate="false"
            boundary-links="true"
            ng-change="pageChanged()">
</pagination>

Inside the pageChanged() function, use the following to create a unique URL for your results page: 在pageChanged()函数内,使用以下命令为结果页面创建唯一的URL:

** My code is on Coffeescript, but the logic is simple and the code easy to adapt ** **我的代码在Coffeescript上,但逻辑很简单,代码很容易适应**

$location.search('page', $scope.Controls.currentPage)

And on your controller, use the following to check, when starting, if the URL parameter is there: 在您的控制器上,使用以下内容检查启动时是否存在URL参数:

urlParams = $location.search()
if urlParams.page?
  $scope.Controls.currentPage = urlParams.page
else
  $scope.Controls.currentPage = 1

Yes, if you want your app to allow linking into certain states then you will have to have your app leverage the routeProvider. 是的,如果您希望您的应用允许链接到某些状态,那么您必须让您的应用利用routeProvider。

The official docs don't have a great deal of information on routes but the tutorial has this page: 官方文档没有关于路线的大量信息,但教程有这个页面:

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

Also John Lindquist's excellent short video tutorials are a must watch. John Lindquist的优秀短视频教程也是值得关注的。 One dealing with routes is: 处理路线的一个是:

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

Here the generic solution - the uibPagination directive decorator and the updated template: 这里是通用解决方案 - uibPagination指令装饰器和更新的模板:

angular.module('ui.bootstrap.pagination')
    .config(function($provide) {
        $provide.decorator('uibPaginationDirective', function($delegate, $templateCache) {
            var directive = $delegate[0];
            directive.scope.getPageHref = "&";
            $templateCache.put("uib/template/pagination/pagination.html",
                "<li ng-if=\"::boundaryLinks\" ng-class=\"{disabled: noPrevious()||ngDisabled}\" class=\"pagination-first\"><a ng-href=\"{{noPrevious() ? '' : getPageHref()(1)}}\" ng-disabled=\"noPrevious()||ngDisabled\" uib-tabindex-toggle>{{::getText('first')}}</a></li>\n" +
                "<li ng-if=\"::directionLinks\" ng-class=\"{disabled: noPrevious()||ngDisabled}\" class=\"pagination-prev\"><a ng-href=\"{{noPrevious() ? '' : getPageHref()(page - 1)}}\" ng-disabled=\"noPrevious()||ngDisabled\" uib-tabindex-toggle>{{::getText('previous')}}</a></li>\n" +
                "<li ng-repeat=\"page in pages track by $index\" ng-class=\"{active: page.active,disabled: ngDisabled&&!page.active}\" class=\"pagination-page\"><a ng-href=\"{{getPageHref()(page.number)}}\" ng-disabled=\"ngDisabled&&!page.active\" uib-tabindex-toggle>{{page.text}}</a></li>\n" +
                "<li ng-if=\"::directionLinks\" ng-class=\"{disabled: noNext()||ngDisabled}\" class=\"pagination-next\"><a ng-href=\"{{noNext() ? '' : getPageHref()(page + 1)}}\" ng-disabled=\"noNext()||ngDisabled\" uib-tabindex-toggle>{{::getText('next')}}</a></li>\n" +
                "<li ng-if=\"::boundaryLinks\" ng-class=\"{disabled: noNext()||ngDisabled}\" class=\"pagination-last\"><a ng-href=\"{{noNext() ? '' : getPageHref()(totalPages)}}\"  ng-disabled=\"noNext()||ngDisabled\" uib-tabindex-toggle>{{::getText('last')}}</a></li>\n" +
                "");
            return $delegate;
        });
    });

We decorate the directive with the getPageHref function passed from the outer scope which is used to construct the page links. 我们使用从外部作用域传递的getPageHref函数来装饰该指令,该作用域用于构造页面链接。

Usage: 用法:

<div ng-controller="ProductController">
    ...
    <ul uib-pagination
        total-items="totalItems"
        ng-model="page"
        get-page-href="getPageHref">
    </ul>
</div>

Now you have to define the getPageHref function in your outer scope: 现在,您必须在外部作用域中定义getPageHref函数:

angular.module('app')
.controller('ProductController', function($scope) {
    ...
    $scope.getPageHref = function(page) {
        return '#/products?page=' + page;
    };
});

Just to make code look better you can use template-url attribute on uib-pagination element to specify your new template url 只是为了使代码看起来更好,您可以在uib-pagination元素上使用template-url属性来指定新的模板URL

I whould use ui-sref instead of using a function to generate the link . 我应该使用ui-sref而不是使用函数来生成链接。

and instead of reloading the controller for each page click pass a function for ng-click with $event so you could prevent the href from been executed with e.preventDefault() and calling your ajax before 而不是为每个页面重新加载控制器单击传递一个函数,使用$event进行ng-click ,这样你就可以防止使用e.preventDefault()执行href并在之前调用你的ajax

<li ng-repeat="page in pages track by $index" ng-class="{active: page.active}"><a ui-sref="list({page: page.text})"  ng-click="$root.paginationClick(page.number,$event)">{{page.text}}</a></li>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM