-->

Angular Table sorting does not work if i use a dif

2019-09-16 14:34发布

问题:

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/posts

and added isArray : true

  var Api = $resource("https://jsonplaceholder.typicode.com/posts", {}, {
    'get': { method: 'GET', isArray: true}
});

in html i took out all the columns and kept "id" column for simplicity

it loads id column but searching sorting does not work.

what is it that i am doing wrong ?

changed pen is here

http://codepen.io/raasmasood/pen/zoeMgx

回答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 :)



回答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;