How can I do pagination with ng-table?

My code

$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, everything is fine. But this is because I hardcoded total , which obviously does not make sense. 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 calls the http request twice for some reason. So what is the right way to do this?

+5
source share
2 answers

Assuming 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 initialize the ng-table options you want.

Using the $http service, you will receive data only ONE TIME if the request is successful, and inside this service, initialize ngTableParams. This way you avoid multiple callback problems.

Notice also the changes in the getData part, how ordering and filtering are resolved with pagination.

Here is the solution I used for my projects, hope this 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())); } }); }); 
0
source

I am not sure if your problem will be solved below, but I use the code below and do not cause a double call problem

  getData: function ($defer, params) { if (timeout) $timeout.cancel(timeout); timeout = $timeout(function () { callback().then(function (data) { params.total(data.TotalCount); $defer.resolve(data.PageData); }); }, 700); } 

Note: the code inserted above is part of the directive, $ timeout is to avoid multiple calls (throttling) and callback() makes the actual call to $ http.

The important part for you here may be: $defer.resolve(data.PageData) does the trick for me there is also no return , as it is in your case.

0
source

Source: https://habr.com/ru/post/1244663/


All Articles