angularjs - 使用angularjs ui bootstrap分页重新加载后如何留在当前页面上?

标签 angularjs angular-ui-bootstrap

下面是我使用 angularjs-ui-bootstrap 进行简单分页的代码。由于我要处理的数据集太大而无法在客户端显示页面,因此我只是在页面更改时抓取每页的数据。

我遇到的问题是,当页面重新加载时,分页总是重置为第一页。如何在页面重新加载时让它停留在当前页面?

html

<uib-pagination total-items="totalCount" ng-model="currentPage" ng-change="pageChanged()" items-per-page="2"></uib-pagination>

JavaScript

    $scope.currentPage = $location.search().page;

    getData($scope.currentPage);

    $scope.pageChanged = function () {
        getData($scope.currentPage);
        $location.url('?page=' + $scope.currentPage);
    };

    function getData(pageNumber) {        
        if (pageNumber == null)
            pageNumber = 1;
        $http.get('http://localhost.angulartestapi.com/v1/AngularTestApi/getteams?pageNumber=' + pageNumber)
        .success(function (data) {
                $scope.teams = data.Teams;
                $scope.totalCount = data.TotalCount;
            }).error(function () {
            alert("error");
        });

此代码当前向 url 添加一个 ?page={currentPage} 参数。当页面重新加载时,它从 $location.search().page 获取保存的页面,并进入 getData() 并设置 $scope.currentPage到正确的页码。但随后它进入 pageChanged() 并且 $scope.currentPage 重置回 1

编辑 Cookie 方法

所以我尝试将 currentPage 保存在这样的 cookie 中:

    $scope.currentPage = $cookies.get('page');

    getData($scope.currentPage);

    $scope.pageChanged = function () {
        getData($scope.currentPage);
        $cookies.put('page', $scope.currentPage);
    };       

当页面重新加载时,它从 cookie 中获取保存的页面并进入 getData() 并将 $scope.currentPage 设置为正确的页码。但随后它进入 pageChanged() 并且 $scope.currentPage 重置回 1。所以问题仍然存在。

编辑 2:

即使 $scope.currentPage 被硬编码为 2,当页面重新加载时 $scope.currentPage 被重置为 1$scope.pageChanged 中。

    $scope.currentPage = 2;

    getData($scope.currentPage);

    $scope.pageChanged = function () {
        getData($scope.currentPage);            
    };       

最终编辑:

找到了留在当前页面的方法。答案如下。

最佳答案

您可以使用浏览器中的localStorage 来保存当前页面,并在以后需要时获取当前页面。

$scope.currentPage = 1;
localStorage.StoreCurrentPage = $scope.currentPage; 
if(localStorage.StoreCurrentPage){
    $scope.currentPage = localStorage.StoreCurrentPage;
}else{
    $scope.currentPage = 1;
}

关于angularjs - 使用angularjs ui bootstrap分页重新加载后如何留在当前页面上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37466285/

相关文章:

angular - 如何使用 ng-bootstrap 在 angular2 中使用 uib-tabset?

css - 更改 Angular Timepicker 字体大小

javascript - AngularJS bootstrap popover 自定义指令

javascript - Angular js ng-class错误条件在ng-repeat中不起作用

css - 使用 AngularJS 和 Jade 在导航栏中 Bootstrap 下拉菜单

angularjs - 用于 Bootstrap 弹出窗口的 Angular 指令

css - 根据设备动态加载 ratchet android/iPhone css 主题

javascript - AngularJS 中的动态下拉列表 uib-typeahead

angularjs - Angular Bootstrap UI 轮播和 Angular 1.3.15

javascript - Angular-UI 模态解析