gpt4 book ai didi

javascript - 如何使用 ng-table 进行服务器端分页?

转载 作者:数据小太阳 更新时间:2023-10-29 05:38:01 27 4
gpt4 key购买 nike

我的代码是

$scope.loadQuestions = function() {
$scope.questionCount = 0;
$scope.questionTable = new NgTableParams({
count: []
}, {
total: 19387,
getData: function($defer, params) {
$scope.filter.sort = params.orderBy();
$scope.filter.page = params.page();
return $http.get("/api/questions", {
params: $scope.filter
}).then(function(response) {
$scope.questionCount = response.data.count;
return response.data.questions;
});
}
});
};

如果我这样做,那很好。但那是因为我对 total 进行了硬编码,这显然没有意义。如果我这样做

  return $http.get("/api/questions", {
params: $scope.filter
}).then(function(response) {
params.total(response.data.count);
$scope.questionCount = response.data.count;
return response.data.questions;
});

然后 ng-table 出于某种原因两次触发 http 请求。那么正确的做法是什么?

最佳答案

假设您使用的是旧版本的 ng-table 脚本,第一步是从您的 api 服务获取数据,然后为 初始化参数ng-table 你想要的。

使用 $http 服务,如果请求成功,您将仅一次 获取数据,并且在该服务中初始化您的 ngTableParams。因此,您将避免出现多个回调的问题。

另请注意 getData 中的更改部分,排序和过滤是如何通过分页解决的。

这是我在项目中使用的解决方案,希望对您有所帮助。

$http.get('/api/questions').success(function (data) {
$scope.questionTable = new ngTableParams({
page: 1,
count: 10
},
{
total: data.length,
getData: function ($defer, params) {
var filteredData = params.filter() ? $filter('filter')(data, params.filter()) : data;
var orderedData = params.sorting() ? $filter('orderBy')(filteredData, params.orderBy()) : data;
params.total(orderedData.length);
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
});
});

关于javascript - 如何使用 ng-table 进行服务器端分页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35869779/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com