Search code examples
javascriptangularjssortingangular-ui-gridui-grid

Sorting of uI grid column containing Angular filter


I have recently started using Angular ui-grid. I am not very well versed with the internals of the library.

I had a ui-grid column that required to display percentages. SO I added the following filter to my app and used it along with ui-grid cellFilter property.

module.filter('percentage', function () {
    return function (input) {
        if (!input) {
            return '';
        } else {
            return input + '%';
        }
    };
})

This worked fine, but while sorting this column. The sorting works unexpectedly. Suppose if I have 3 rows with values 100,200,300. I expect it can have only two sorted states 100,200,300 and 300,200,100. But if I keep clicking the header of this column I get a third state as 200, 300, 100 or as 100, 300,200. I am even not sure what the pattern is for this state.

If I am right, The angular filter works only on the views and do not impact model of the field. So I do not think adding filter can have an impact on sorting.

Apart from that the two expected sorting (ASCENDING, DESCENDING) appears perfectly, the only problem being the appearance of third. How do I resolve this issue.

Am I missing any implementation ?? Kindly help me resolve this.

Edit: This issue occurs for string column as well. In my understanding there can only be one ASCENDING and one DESCENDING state as far as sorting is considered. But I get more arrangements.


Solution

  • You can use sortDirectionCycle to remove the third state of sorting.

    columnDefs: [
       { field: 'name', sortDirectionCycle: [uiGridConstants.ASC, uiGridConstants.DESC] },
       { field: 'gender', sortDirectionCycle: [uiGridConstants.ASC, uiGridConstants.DESC] },
       { field: 'company', enableSorting: false }
    ]
    

    From document, When clicking on a column heading the sort direction will cycle to ascending, then descending, then back to unsorted. You may rearrange this cycle or skip part of it by setting the sortDirectionCycle columnDef option. For more details check this link sortDirectionCycle