Search code examples
javascriptangularjsangular-resourcengtable

ng-Table sorting and searching not working when use $resource


i started with an existing example of ngTable an modified it a bit to use ngResource. using resource factory it populates the data but searching and sorting doesn't works.

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

Created a pen above.

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

app.factory('orderResource', function ($resource) {
    return $resource('https://jsonplaceholder.typicode.com/posts');
});

(function () {

    app.controller("demoController", demoController);
    demoController.$inject = ["NgTableParams", "$resource", "orderResource"];
    function demoController(NgTableParams, $resource, orderResource) {
        //debugger;
        var ordersGet = orderResource.query({ });


        var Api = $resource("/data");
        this.tableParams = new NgTableParams({}, {
            getData: function (params) {

                // **** Section 1 ***  sorting and filter does not work
                    return ordersGet.$promise.then(function (response) {
                    params.total(100);
                    return response;
              // **** Section 1 *** 
              
              
                //****Section 2 *** this works fine
                    // return Api.get(params.url()).$promise.then(function(data) {
                    //           params.total(data.inlineCount);  
                    //           return data.results;
              //****Section 2 ***
              
              
                });
            }
        });
    }
})();
<div ng-app="myApp">
    <div ng-controller="demoController as demo">



        <table ng-table="demo.tableParams" class="table table-bordered table-striped table-condensed">
            <tr ng-repeat="row in $data track by row.id">
                <td data-title="'iss'" filter="{id: 'number'}" sortable="'id'">{{row.id}}</td>

            </tr>
        </table>
    </div>
</div>

In the code if you comment section 1 and un comment section 2 you can observe it working. i also tried simple $http it didn't worked as well.


Solution

  • Angular Table sorting does not work if i use a different api

    I asked the same question else where and got a better answer.

    First thing was, we were missing filtering.

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

    and to make sorting work we had to add some logic to remove properties with null filter values.

    working code pen is here

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