AabinGunz
AabinGunz

Reputation: 12347

How to filter and sort array elements in ngtable?

I have an array which I am using in ngtable, but need help in filtering data I am not able to do sort when I click on the header. Please help

HTML

<table class="table" ng-table="namingConventionParams" show-filter="true">
    <tr ng-repeat="item in $data | orderBy:'toString()'">
        <td style="word-break:break-all" data-title="items.tableHeader" align="left" filter="{ '0': 'text' }" sortable="'valueOf()[0]'">{{item}}</td>
    </tr>
</table>

Controller

$scope.namingConventionParams = new ngTableParams({
    page: 1, // show first page
    count: 10
}, {
    defaultSort: "asc",
    total: $scope.items.instanceData.length, // length of data
    counts: [],
    getData: function($defer, params) {
        var data = $scope.items.instanceData;
        var orderedData = params.filter() ? $filter('filter')(data, params.filter()) : data;
            orderedData = params.sorting() ? $filter('orderBy')(orderedData, params.orderBy()) : orderedData;
            params.total(orderedData.length);
            $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));            
    }
});

Plunker link

Upvotes: 2

Views: 1438

Answers (1)

Miguel
Miguel

Reputation: 20633

The problem with your code is that your array of data only contains strings instead of objects, so it's filtering based only on the first character when you have sortable="valueOf()[0]"

The solution is to use objects instead. Here is the relevant code that needs to be updated:

HTML

<td ... filter="{'name':'text'}" sortable="name">{{item.name}}</td>

JS

var data = $scope.items.instanceData.map(function(text) {
  return {name: text};
});

Plunker Demo

Upvotes: 1

Related Questions