Search code examples
angularjssortingangular-ui-gridui-grid

Is it possible to bind the sorting of a column to a different property than its display property with Angular UI Grid?


I was just wondering if anyone knew of a way to sort a column in the same order as another column using Angular UI Grid.


Solution

  • I'm guessing you mean that if (for example) you have "First Name" and "Last Name" columns which display first name and last name respectively, you want to click sort on "Last Name" and this actually sorts the table in order of "First Name"?

    If so, you can accomplish this using a cell template.

    Assume you have the following table:

    enter image description here

    and when you sort the "Last Name" column it will actually sort the table in order of the data in the "First Name" column.

    Assuming the following data:

    $scope.gridOptions.data = [{
        "firstName": "David",
        "lastName": "Carney",
    }, {
        "firstName": "Bob",
        "lastName": "Wise",
    }, {
        "firstName": "Peter",
        "lastName": "Thompson",
    }];
    

    Define your columnDefs as follows:

    $scope.gridOptions.columnDefs = [{
        name: 'firstName',
        field: 'firstName'
    }, {
        name: 'lastName',
        field: 'firstName',
        cellTemplate: '<div class="ui-grid-cell-contents">{{row.entity.lastName}}</div>'
    }];
    

    The column definition for the second column names the column "Last Name" and the cell template ensures the lastName attribute is displayed in the cell, however as the column's field is bound to firstName it means when the column is sorted it is sorted on firstName.

    An example can be found here. Sort the second column (Last Name) and the rows will actually be sorted in order of the first column (First Name).