My code is
$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;
});
}
});
};
If I do this, it's fine. But that's because I hardcoded the total
, which doesn't make sense obviously. If I do
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;
});
then it ng-table
fires the http
request twice for some reason. So what's the right way to do it?
In assuming that you are using one of the older versions of ng-table
script, the first step is to get the data from your api service, and then to intialize the parameters for ng-table
that you want.
With $http
service you will get the data only ONE TIME if the request is successful, and inside that service initialize your ngTableParams. So you will avoid problems with multiple callbacks.
Note also the changes in getData part how ordering and filtering are solved with pagination.
Here is the solution that I used for my projects, hope it helps.
$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()));
}
});
});