ng-table icon indicating copy to clipboard operation
ng-table copied to clipboard

Sorting table populated with getData not working

Open jasonok6 opened this issue 10 years ago • 4 comments

Simple example, filtering works as expected when loading table with an array using the dataset property. But, when populating using getData the results won't filter. What am I doing wrong?

http://plnkr.co/edit/wTBElpOBSWxw6URjNPa9?p=preview

jasonok6 avatar Sep 17 '15 15:09 jasonok6

When you supply your own getData function then you will need to apply the filters, sorts and paging yourself.

Typically you would supply a getData function when you want the filters (etc) to run on the server. Here's an example of what they could look like: http://ng-table.com/#/loading/demo-external-array

christianacca avatar Sep 17 '15 21:09 christianacca

@christianacca the problems are: 1. I cannot see what ngTableDemoFakeBackend did and no idea what is the response data from the server should exactly looks like. 2. When trying to insert/delete a row, I was suggested to use param.reload(), and tracking the source code I found that the reload() called the getData(). In this case I don't want to run the filters on the server at all. Create and Delete are the two fundamental operations of any CRUD application. Hope ng-table to natively support them, at least at API level.

zipper01 avatar Nov 15 '17 04:11 zipper01

When you supply your own getData function then you will need to apply the filters, sorts and paging yourself.

Any examples of this in the documentation?

edwinjue avatar Feb 08 '18 20:02 edwinjue

Ok, I figured it out. So, if you do this with server-side data, what happens when you click on a column heading, it will make a call like this to your backend:

GET /data?count=10&page=1&sorting%5Bid%5D=desc

Notice, the URL parameters that get passed in along with the call to /data route. What you need to do is on the backend, parse these query parameters and make use of them to return data sorted accordingly. Since I'm using mongodb, I use something like this on the backend:

when route hits '/data', I call myController.getData to handle the response: router.get('/data', myController.getData);

myController.getData code (where the backend sorting and response takes place):

exports.getData = function(req,res,next){
    var field = "createdAt";
    var direction = -1;

    if(!!req.query.sorting === true){
      var field = Object.keys(req.query.sorting)[0];
      var direction = (req.query.sorting[Object.keys(req.query.sorting)] === "desc") ? -1 : 1;
    }
    var sortObj = {};
    sortObj[field] = direction;

    ModelData.find({}).sort(sortObj).exec(function(err, documents){
        if(err){
            return next(err);
        }
        res.json({"results":documents});
    });
};

Hope this helps someone. If it helps nobody, well, that's ok too

edwinjue avatar Feb 08 '18 21:02 edwinjue