Skip to content Skip to sidebar Skip to footer

Angular Table Sorting Does Not Work If I Use A Different Api

i took ngTable example from http://ng-table.com/#/loading/demo-external-array opened it in code pen and instead of '/data' i am using an api https://jsonplaceholder.typicode.com/

Solution 1:

http://codepen.io/anon/pen/rWRNjQ

you could check this codepen, now it works. ;)

getData: function(params) {
    // ajax request to api
    return Api.get(params.url()).$promise.then(function(data) {
     params.total(100); // recal. page nav controls
     return ($filter('orderBy')(data, params.orderBy()));
      //return data;
    });
  }

Previously there we missed the filter part.

return $filter('filter')($filter('orderBy')(data, params.orderBy()),params.filter());

for enabling filter too :)


Solution 2:

I had the same problem and ended up doing the sort/filter/paging manually:

var app = angular.module("myApp", ["ngTable", "ngResource", "ngTableDemoFakeBackend"]);
(function() {

  app.controller("demoController", demoController);
  demoController.$inject = ["NgTableParams", "$resource", "$filter"];

  function demoController(NgTableParams, $resource, $filter) {
  //var Api = $resource("/data");
    var Api = $resource("https://jsonplaceholder.typicode.com/posts", {}, {
      // Let's make the `query()` method cancellable
      query: {method: 'get', isArray: true, cancellable: true}
    });        

    this.tableParams = new NgTableParams({      
      count: 5
    }, {

      getData: function(params) {
        // ajax request to api
        return Api.query().$promise.then(function(data) {

         params.total(data.length); // recal. page nav controls

          var filteredData = params.filter().id  ?
                      $filter('filter')(data, params.filter()) :
                         data;

          var orderedData = params.sorting() ?
              $filter('orderBy')(filteredData, params.orderBy()) : data;
          var page = orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count());

          return page;
        });
      }
    });

  }
})();

The downside with this approach is since you are using filtering, the more columns you add the more checking you need to do because the way it works, when you clear the filter it will not set that object to undefined. It will create an object like this:

{ id: null }

Which means you cannot use params.filter() in this line:

var filteredData = params.filter().id  ?
                  $filter('filter')(data, params.filter()) :
                     data;

Post a Comment for "Angular Table Sorting Does Not Work If I Use A Different Api"