ngTableParams Pagination with $http.get

后端 未结 1 573
情深已故
情深已故 2021-01-01 07:13

Working on an AngularJS project and I\'ve ran into the following problem:

When using locally stored / hard coded data, the pagination works fine. When using remotely

相关标签:
1条回答
  • 2021-01-01 07:51

    First of all your code is using the local data array as a source in ngTables getData callback and it is not clear what you are presenting as a comparison since you did not actually try AJAX Data Loading from the official examples .

    Instead I would expect it to have an api call to the server using $http.get.

    Remember for server side paging to work you must update the total count each time you query for data because they may have changed. Also you will have to consider a server side solution for sorting as well.

    Here is a working sample using the github api as a test service.

    var app = angular.module('main', ['ngTable']);
    
    app.controller('MainCtrl', function($scope, $http, ngTableParams) {
      $scope.tableParams = new ngTableParams({
                    page: 1,
                    count: 5,
                }, {
                    getData: function ($defer, params) {
                        var page = params.page();
                        var size = params.count();
                        var testUrl = 'https://api.github.com/search/repositories';
                        var search = {
                          q: 'angular',
                          page: page,
                          per_page: size
                        }
                        $http.get(testUrl, { params: search, headers: { 'Content-Type': 'application/json'} })
                             .then(function(res) {
                                params.total(res.data.total_count);
                                $defer.resolve(res.data.items);
                            }, function(reason) {
                                $defer.reject();
                            }
                        );
                    },
                });
    });
    <link href="https://cdnjs.cloudflare.com/ajax/libs/ng-table/0.3.3/ng-table.min.css" rel="stylesheet"/>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ng-table/0.3.3/ng-table.min.js"></script>
    <div  ng-app="main"  ng-controller="MainCtrl">
       <table ng-table="tableParams" class="table table-striped table-bordered table-hover table-condensed">
            <tr ng-repeat="repo in $data">
                <td data-title="'id'">{{repo.id}}</td>
                <td data-title="'name'">{{repo.name}}</td>
                <td data-title="'owner'">{{repo.owner.login}}</td>
            </tr>
    </table> 
    <div>

    0 讨论(0)
提交回复
热议问题