Sort basic data in ng grid

I want to display the formatted value in the ng-grid cell, but sorting by the associated numeric value is not displayed.

var myData1 = [{ name: "Moroni", age: 50, ageWord: "Fifty" } 

In the above example, I would display the ageWord column, but I want to sort by the age column.

The docs for sorting the ng-grid directive indicates that I can provide a custom function for sorting the underlying data:

sortFn

Sets the sort function for a column. Useful if you have data formatted in an unusual way or if you want to sort the underlying data type . Check sample MDN docs for examples

the custom sort function gets the displayed values ​​when I click on the sort column, but I want to sort by age. If I had a string available in the sort function, I could sort in a sibling cell, something like this:

 sortFn: function(a, b) { var ageA = a.getProperty('age'); var ageB = b.getProperty('age'); return ageA-ageB; } 

Any suggestions how can I sort by age when the "ageWord" column is sorted? An example is available at plnkr .

+6
source share
2 answers

You need to define your column as an object and define a cellTemplate . Then use the age property in your sortFn ( http://plnkr.co/edit/qmBsneZ3HmFRKSkjbBWU?p=preview ):

 // main.js var app = angular.module('myApp', ['ngGrid']); app.controller('MyCtrl', function($scope) { //Notice age is now an object to be used with the cellTemplate var myData1 = [{name: "Moroni", age: {age: 50, ageWord: "Fifty"}}, {name: "Tiancum", age: {age: 43, ageWord: "Forty-Three"}}, {name: "Mildred", age: {age: 70, ageWord: "Seventy"}}, {name: "Jacob", age: {age: 27, ageWord: "Twenty-Seven"}}]; $scope.gridOptions = { data: 'gridData', columnDefs: [ {field: 'name', displayName: 'Name'}, {field:'age', displayName:'Age', cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><span ng-cell-text>{{COL_FIELD.ageWord}}</span></div>', sortFn: function (a, b) { //compare age property of the object if (a.age < b.age) { return -1; } else if (a.age > b.age) { return 1; } else { return 0; } } }] }; $scope.gridData = myData1; }); 

According to the default cellTemplate docs:

 <div class="ngCellText" ng-class="col.colIndex()"><span ng-cell-text>{{COL_FIELD CUSTOM_FILTERS}}</span></div> 

So, all you have to do is use {{COL_FIELD.age}} and any custom filters that you may (or may not) have.

+13
source

You can use sortInfo in your gridOptions , for example:

  $scope.gridOptions = { data: 'gridData', columnDefs: [ {field: 'name', displayName: 'Name'}, {field:'ageWord', displayName: 'Age'} ], sortInfo: { fields: ['age'], directions: ['asc'] } }; 
+5
source

All Articles