使用 $http.get 进行 ngTableParams 分页 [英] ngTableParams Pagination with $http.get

查看:26
本文介绍了使用 $http.get 进行 ngTableParams 分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在处理 AngularJS 项目时遇到了以下问题:

当使用本地存储/硬编码数据时,分页工作正常.使用远程存储的数据时,分页无法正常工作.

我已经搜索了很多,但找不到解决我的问题的方法,所以这里是代码片段:

HTML:

<p><strong>页面:</strong>{{tableParams.page()}}</p><p><strong>Aantal weergegeven:</strong>{{tableParams.count()}}</p><table ng-table="tableParams" class="table table-striped" template-pagination="custom/pager"><tr ng-repeat="x 名称"><td data-title="'Name'">{{x.Name}}</td><td data-title="'City'">{{x.City}}</td><td data-title="'Country'">{{x.Country}}</td></tr><script type="text/ng-template" id="custom/pager"><ul class="pager ng-cloak"><li ng-repeat="一页一页"ng-class="{'disabled': !page.active, 'previous': page.type == 'prev', 'next': page.type == 'next'}"ng-show="page.type == 'prev' || page.type == 'next'" ng-switch="page.type"><a ng-switch-when="prev" ng-click="params.page(page.number)" href="">&laquo;上一个<a ng-switch-when="next" ng-click="params.page(page.number)" href="">Next &raquo;</a><li><div class="btn-group"><button type="button" ng-class="{'active':params.count() == 2}" ng-click="params.count(2)" class="btn btn-default">2<button type="button" ng-class="{'active':params.count() == 5}" ng-click="params.count(5)" class="btn btn-default">5<button type="button" ng-class="{'active':params.count() == 10}" ng-click="params.count(10)" class="btn btn-default">10<button type="button" ng-class="{'active':params.count() == 15}" ng-click="params.count(15)" class="btn btn-default">15

JS:

app.controller('ngTableCtrl2', function ($scope, $http, $filter, ngTableParams) {$http.get('http://www.w3schools.com/angular/customers.php').success(function (response) {$scope.names = response.records;});$scope.tableParams = 新的 ngTableParams({page: 1,//显示第一页count: 5,//每页计数排序:{name: 'asc'//初始排序}}, {total: data.length,//数据长度getData: 函数 ($defer, params) {//使用内置角度过滤器varorderedData = params.sorting() ?$filter('orderBy')(data, params.orderBy()) : 数据;$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));}});});

网页(直播版:http://178.62.232.175:8080/STANDARD/#/app/table/data ) 显示第一个表中的所有结果(远程,来自 $http.get),而第二个表只显示设置的结果?!(2, 5, 10, 15)代码是相同的,除了:

用于显示远程数据,替换为:

显示原始数据:

var 数据 = [{名称:Alfreds Futterkiste",城市:柏林",国家:德国"},{名称:Ana Trujillo Emparedados",城市:México D.F.",国家:Mexico"},{名称:Antonio Moreno Taquería",城市:México D.F.",国家:Mexico"},{名称:环绕号角",城市:伦敦",国家:英国"},{名称:B's Beverages",城市:伦敦",国家:英国"},{名称:Berglunds snabbköp",城市:Luleå",国家:瑞典"},{名称:Blauer See Delikatessen",城市:曼海姆",国家:德国"},{名称:Blondel père et fils",城市:斯特拉斯堡",国家:法国"},{名称:Bólido Comidas preparadas",城市:马德里",国家:西班牙"},{名称:Bon app",城市:马赛",国家:法国"},{名称:Bottom-Dollar Marketse",城市:Tsawassen",国家:加拿大"},{名称:Cactus Comidas para llevar",城市:布宜诺斯艾利斯",国家:阿根廷"}];

第二个表的分页正常工作.我必须编辑哪些内容才能使用远程数据?

解决方案

首先你的代码在 ngTables getData 回调中使用本地数据数组作为源,不清楚你是什么由于您实际上并没有尝试从官方示例中AJAX 数据加载,因此作为比较呈现.

相反,我希望它使用 $http.get 对服务器进行 api 调用.

请记住,要使服务器端分页正常工作,您必须在每次查询数据时更新总计数,因为它们可能已更改.此外,您还必须考虑使用服务器端解决方案进行排序.

这是一个使用 github api 作为测试服务的工作示例.

var app = angular.module('main', ['ngTable']);app.controller('MainCtrl', function($scope, $http, ngTableParams) {$scope.tableParams = 新的 ngTableParams({页数:1,数:5,}, {getData: 函数 ($defer, params) {var page = params.page();var size = params.count();var testUrl = 'https://api.github.com/search/repositories';无功搜索 = {q:'角度',页:页,每页:大小}$http.get(testUrl, { params: search, headers: { 'Content-Type': 'application/json'} }).then(功能(资源){params.total(res.data.total_count);$defer.resolve(res.data.items);}, 函数(原因){$defer.reject();});},});});

<link href="https://cdnjs.cloudflare.com/ajax/libs/ng-table/0.3.3/ng-table.min.css" rel="样式表"/><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>

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 stored data, the pagination does not work properly.

I have searched quite a bit, but couldn't find the solution to my problem, so here are the code snippits:

The HTML:

<div ng-controller="ngTableCtrl">
    <p><strong>Pagina:</strong> {{tableParams.page()}}</p>
    <p><strong>Aantal weergegeven:</strong> {{tableParams.count()}}</p>

    <table ng-table="tableParams" class="table table-striped" template-pagination="custom/pager">
        <tr ng-repeat="x in names">
            <td data-title="'Name'">{{x.Name}}</td>
            <td data-title="'City'">{{x.City}}</td>
            <td data-title="'Country'">{{x.Country}}</td>
        </tr>
    </table>

    <script type="text/ng-template" id="custom/pager">
        <ul class="pager ng-cloak">
            <li ng-repeat="page in pages"
                ng-class="{'disabled': !page.active, 'previous': page.type == 'prev', 'next': page.type == 'next'}"
                ng-show="page.type == 'prev' || page.type == 'next'" ng-switch="page.type">
                <a ng-switch-when="prev" ng-click="params.page(page.number)" href="">&laquo; Previous</a>
                <a ng-switch-when="next" ng-click="params.page(page.number)" href="">Next &raquo;</a>
            </li>
            <li>
                <div class="btn-group">
                    <button type="button" ng-class="{'active':params.count() == 2}" ng-click="params.count(2)" class="btn btn-default">2</button>
                    <button type="button" ng-class="{'active':params.count() == 5}" ng-click="params.count(5)" class="btn btn-default">5</button>
                    <button type="button" ng-class="{'active':params.count() == 10}" ng-click="params.count(10)" class="btn btn-default">10</button>
                    <button type="button" ng-class="{'active':params.count() == 15}" ng-click="params.count(15)" class="btn btn-default">15</button>
                </div>
            </li>
        </ul>
    </script>
</div>

The JS:

app.controller('ngTableCtrl2', function ($scope, $http, $filter, ngTableParams) {

    $http.get('http://www.w3schools.com/angular/customers.php')
    .success(function (response) {$scope.names = response.records;});

    $scope.tableParams = new ngTableParams({
        page: 1, // show first page
        count: 5, // count per page
        sorting: {
            name: 'asc' // initial sorting
        }
    }, {
        total: data.length, // length of data
        getData: function ($defer, params) {
            // use build-in angular filter
            var orderedData = params.sorting() ? $filter('orderBy')(data, params.orderBy()) : data;
            $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
        }
    });
});

The webpage ( live version: http://178.62.232.175:8080/STANDARD/#/app/table/data ) shows all results in the first table (remote, from $http.get), whilst the second table, shows only the set results?! (2, 5, 10, 15) The code is identical, except for:

<tr ng-repeat="x in names">

used to display remote data and is replaced by:

<tr ng-repeat="x in $data">

to display raw data as such:

var data = [{
Name: "Alfreds Futterkiste", City: "Berlin", Country: "Germany"},{
Name: "Ana Trujillo Emparedados", City: "México D.F.", Country: "Mexico"},{
Name: "Antonio Moreno Taquería", City: "México D.F.", Country: "Mexico"},{
Name: "Around the Horn", City: "London", Country: "UK"},{
Name: "B's Beverages", City: "London", Country: "UK"},{
Name: "Berglunds snabbköp", City: "Luleå", Country: "Sweden"},{
Name: "Blauer See Delikatessen", City: "Mannheim", Country: "Germany"},{
Name: "Blondel père et fils", City: "Strasbourg", Country: "France"},{
Name: "Bólido Comidas preparadas", City: "Madrid", Country: "Spain"},{
Name: "Bon app", City: "Marseille", Country: "France"},{
Name: "Bottom-Dollar Marketse", City: "Tsawassen", Country: "Canada"},{
Name: "Cactus Comidas para llevar", City: "Buenos Aires", Country: "Argentina"}
];

The pagination of the second table works as it should. What must I edit to make it work with remote data?

解决方案

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>

这篇关于使用 $http.get 进行 ngTableParams 分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆