Sorting in Angular's UI-Grid based on a custom column instead of the default field value

One of the tables in my database is called Job:

name    nvarchar(50)
id  int
description nvarchar(50)
enabled bit
date_modified   datetime
user    nvarchar(50)

Here is the corresponding class structure:

public class Job {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public bool Enabled { get; set; }
    public DateTime DateModified { get; set; }
    public string User { get; set; }
}

Currently, I am working on an application using Angular and TypeScript. I have encountered a problem while trying to display data:

I am utilizing the ui-grid component from Angular for the grid layout. The column definitions are as follows:

    columnDefs: [
        {
            field: 'id',
            defaultFilter: FilterOperator.EQU,
            sort: {

                direction: this.uiGridConstants.DESC,
                priority: 0,
            },
            type: 'number'
        },
        { field: 'name', defaultFilter: FilterOperator.LIKE, sort: null },
        { field: 'description', defaultFilter: FilterOperator.LIKE, sort: null },
        { field: 'enabled', filter: { type: 'select', selectOptions: [{ value: true, label: 'True' }, { value: false, label: 'False' }] } },
        { field: 'user', defaultFilter: FilterOperator.LIKE, sort: null },
        { field: 'date_modified', type: 'date', enableFiltering: false, sort: null, cellTemplate: '<div>{{row.entity.dateModified | date:\'dd/MM/yyyy hh:mm:ss\'}}</div>' },
        { field: 'action', enableFiltering: false, enableSorting: false, sort: null, cellTemplate: `${this.baseUrl}app/automaticAction/listActionsTemplate.html` }
    ]

The issue I am facing is related to sorting the 'date modified' column. To sort it correctly, I need the field property value to match the database column (date_modified), but for displaying data, I need to use the class property (dateModified). Is there a way to extend or modify the column definitions to specify the desired column for sorting? I am currently using a workaround with celltemplate, but I am open to better solutions.

Answer №1

A custom sortingAlgorithm property can be specified in the columnDef...

{ field: 'DateModified', type: 'date', enableFiltering: false, sort: null, cellTemplate: '<div>{{row.entity.DateModified | date:\'dd/MM/yyyy hh:mm:ss\'}}</div>', sortingAlgorithm: YourCustomService.getDateSortingAlgorithm() },

Define the sorting algorithm in a service (or scope) like this

getDateSortingAlgorithm: function () {
    return function (aDate, bDate) {
        var dateDisplayFormat = 'dd/MM/yyyy hh:mm:ss';
        var aMoment = moment(aDate, dateDisplayFormat);
        var bMoment = moment(bDate, dateDisplayFormat);
        if (aMoment.isBefore(bMoment)) {
            return -1;
        } else if (bMoment.isBefore(aMoment)) {
            return 1;
        } else {
            return 0;
        }
     }
},

If you are not using moment, feel free to adjust the algorithm to meet your needs.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for maintaining the active state of an item within a component that loops through a dataset

I am working with an array of objects (specifically, posts represented as strings) and I am looking to be able to edit each one individually. However, I am encountering an issue where clicking on the edit button triggers editing for all posts at once: co ...

Navigating through different views in your AngularJS application using the

I am facing an issue with UI router where the view of the first page is not opening, and I am unsure why it's not showing the template. Currently, only the index.html element is displayed. Any assistance would be greatly appreciated as I'm new to ...

The element is inferred to have an 'any' type due to the inability to use a 'string' type expression to index the 'Palette' type

Encountering an issue: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Palette'. No index signature with a parameter of type 'string' was found on type &ap ...

"Exploring the world of mocking module functions in Jest

I have been working on making assertions with jest mocked functions, and here is the code I am using: const mockSaveProduct = jest.fn((product) => { //some logic return }); jest.mock('./db', () => ({ saveProduct: mockSaveProduct })); ...

Angular.js $resource output

I noticed an unusual behavior with Angular $resource. Take a look at the code below: class Service constructor: ($resource) -> service = $resource '/record/:id' Service::list = (cb) -> s ...

What is the method for obtaining the previous URL in the route history that is different from the current URL?

I have implemented a button on my application that allows the user to navigate back to the previous page. Here is how it's set up: <button ng-click="goBack()">Go back</button> $scope.goBack = function() { $window.history.back(); ...

Is it possible to validate a template-driven form without using the model-driven approach?

Attempting to validate a template-driven form in Angular without two-way data binding has proved to be challenging. I have successfully implemented validation using [(ngModel)], but running into an error when trying to validate the form without the MODEL p ...

Unable to access specific data from the JSON string retrieved from the backend, as it is returning a value of undefined

After receiving a JSON string from the backend, my frontend is encountering issues when trying to index it post using JSON.parse(). The indexed value keeps returning as undefined, even though it's a JSON object literal and not within an array. For th ...

Is there a way to incorporate untyped ES6 react components into a Typescript component without specifying types for the JavaScript child components?

Imagine you have an ES6 component structured like this: component OldThing extends React.Component { constructor(props) { super(props); } render() { return <div>{this.props.someProp}</div>; } } Alongside, there's an ES6 ...

Minimize the occurrence of errors by focusing on parameter piping transformations in Angular

Recently, I created a custom transform pipe in order to condense a collection of objects. The implementation of the SumPipe looks like this: export class SumPipe implements PipeTransform { transform(items: ListCount[], attr: string): number { return ...

Multiple setup calls in Braintree result in receiving multiple onPaymentMethodReceived events

In my Angular application, I am working with an angularUI modal window where I want to integrate the Drop In form provided by Braintree for processing payments. To achieve this, I have created a standard form (partial.html): <form id="creditCard" > ...

Navigating between components in angular2 modules: A tutorial

Currently, I am utilizing angular2 Final version for my development tasks. Within my project, I have established 3 distinct modules: AppModule ProjectModule DesignerModule In the past, I solely had AppModule which integrated the following RoutingModule ...

The URL being called by $http.get is incorrect

Attempting to invoke a URL through my AngularJS service, I have encountered an issue where a particular call is not reaching the intended URL. The following code snippet depicts the function responsible for making the call, along with a console.log statem ...

Comparing type assertions and properties

I have observed the following behavior: interface Person { name: string; age: number; } let person:Person = { name: "Alice", age: 25 } If I do not include age: 25, I will receive a compilation error. This is the expected behavior. Howev ...

The console is showing an Error [ERR_HTTP_HEADERS_SENT] because headers cannot be set after they have already been sent to the client

I'm struggling to figure out how to resolve this issue. Interestingly, when I use PostMan to send data, everything is saved successfully and the task is completed without any problems. However, I see this error in the console. If I remove the .json(t ...

How to Halt or Keep Running a For Loop in Angular 2/4?

for (let index = 0; index < this.selectedFileType[i].count; index++) { this.modal.show(); } My goal is to display the modal each time it enters the loop, and then proceed with the loop after closing the modal. ...

Subsequent to a certain period, the root scope variables become void

Currently, I am in the process of developing an application using Ionic that is supposed to store various variables - such as rootScope variables - at the time of login and then utilize these stored variables for HTTP requests throughout the duration of th ...

Is the AngularJS email validation triggering too soon?

My challenge involves validating an email field in angularjs using the following code: <input type="email" ng-model="email" class="form-control" name="email" ng-required="true" placeholder="Email Address"> <span ng-show="loginForm.email.$touched ...

Implementing custom object property filtering in Angular typeahead

I'm currently working on integrating a versatile typeahead directive. This directive requires a list of options and a configuration object as attributes. Within the configuration object, there is a property called "label" which dictates what the user ...

What is the best way to monitor updates made to a function that utilizes firestore's onSnapShot method?

I am currently working with the following function: public GetExercisePosts(user: User): ExercisePost[] { const exercisePosts = new Array<ExercisePost>(); firebase.firestore().collection('exercise-posts').where('created-by&apo ...