The orderBy feature in AngularJS does not seem to be functioning properly when using a

Recently, I have developed a custom function to determine the "fromNow" value using Moment and now I am looking to organize the data based on this function's output.

I aim to place the Table Element at the top where the Days from Now are fewer.

In the table below, the entry for 31 Days From Today in the 2nd column is lower, and I want to prioritize this element. However, my attempts so far have been unsuccessful.

Could someone assist me with this sorting task? Table

View Table Demo

Utilizing AngularJS OrderBy:

<tr ng-repeat="x in Holidays|orderBy:findFromNow">
                <td>{{$index+1}}</td>
                <td>{{x.Day}}</td>
                <td>
                <span class="label label-warning">{{findFromNow(x.Date)}} Days From Today</span></td>
                </tr>

Custom Function:

$scope.findFromNow = function (inputDate) {
        var m = moment(inputDate, "D-MMM-YY");
        var today = moment().startOf('day');
        var days = Math.round((today - m) / 86400000);
        if (days > 0) {
            return 999;
        } else {
            return (days * (-1));
        }

    }

Holidays JSON:

  [
    {
      "Day": "Monday",
      "Date": "2-Jan-17"
    },
    {
      "Day": "Monday",
      "Date": "20-Feb-17"
    },
    {
      "Day": "Monday",
      "Date": "29-May-17"
    },
    {
      "Day": "Monday",
      "Date": "3-Jul-17"
    },
    {
      "Day": "Tuesday",
      "Date": "4-Jul-17"
    },
    {
      "Day": "Monday",
      "Date": "4-Sep-17"
    },
    {
      "Day": "Thursday",
      "Date": "23-Nov-17"
    },
    {
      "Day": "Friday",
      "Date": "24-Nov-17"
    },
    {
      "Day": "Monday",
      "Date": "25-Dec-17"
    }
  ]

Answer №1

If you want to use moment in orderBy, be sure to write a separate function or check the type of inputDate first. Keep in mind that in this context, inputDate is an Object and not a Date.

 $scope.sortDate = function(inputDate){
    var m = moment(inputDate.Date, "D-MMM-YY");
    var today = moment().startOf('day');
    var days = Math.round((today - m) / 86400000);
    if (days > 0) {
        return 999;
    } else {
        return (days * (-1));
    }

}

Check out the plnkr for more details:

http://plnkr.co/edit/afgsPDBF5RXG5WviYrdU?p=preview

I hope this explanation helps clarify things for you.

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

Vue select is causing the selected choice of another selector to be influenced

Currently, I am facing an issue with a table displaying a specific Nova resource. The problem lies in the selectors within each row of the table - when one selector is changed, all other selectors automatically mirror that change. This behavior seems to be ...

Refreshing modal content following successful AJAX call

Does anyone know how to fix this issue in my code? I need to reload a modal for another database query after a successful operation if(result === 'success'){ $("#editarModalOcup").modal('hide'); $('#success .modal-body'). ...

"Return to previous view with the zoom back feature in CanvasJS

How can I implement a zoom back button in CanvasJS using jQuery or normal JavaScript? I've been attempting to place it near the ones in the top right corner, but something seems to be amiss. Alternatively, is it feasible to enable zooming in and out ...

componentWillReceiveProps with excessive conditional statements

Having recently ventured into React development, I've already worked on 3 major projects utilizing React+Redux. However, I've noticed a recurring pattern that I find quite displeasing: componentWillReceiveProps(nextProps) { if (nextProps.par ...

Searching through nested JSON data in an Angular application

I have a dynamic menu generated from a JSON object which looks like this: [ { "name":"Menu Item 1", "id":"8", "children":[ { "name":"Sub Menu 1-1", "id":"1", "children":[ ...

Help kids find solutions

Here is the HTML code I am working with: <div class = "touch" onclick="do(this)"> <span>text01</span> <span>text02</span> <span>text03</span> <span>text04</span> <div class = "findMe">a ...

A technique for making the placeholder flash when an input textfield loses focus

I am trying to implement a blinking effect on the placeholder text when the input field loses focus. Here is the HTML code I have written: <input type="text" id="keyfob" class="customform col-sm-12 text-red" data-required='true' placeholder= ...

Adding an external script to a Vue.js template

Delving into the world of Vue.js and web-pack, I opted to utilize the vue-cli (webpack) for scaffolding an initial application. A challenge arose when attempting to incorporate an external script (e.g <script src="...") in a template that isn't req ...

Refreshing a query in the AngularJS REST resource

Is there a way to update the results of an AngularJS $resource query without refreshing the entire page? Here is what my current page looks like: <div class="container" ng-controller="AppController"> <div ng-repeat="tile in items"> < ...

Working with arrays and elements in JavaScript using regular expressions

The programming language is JavaScript. Imagine we have an array filled with positive and negative integers mixed in with other letters (e.g. 1a or -2d). The challenge is to figure out how to select all the strings that start with or contain positive inte ...

Is there a way to prevent the "undefined" message from displaying in the console when this code is run?

Help needed! Can someone assist me in resolving the issue where the word 'undefined' is being displayed in the console? I'm a beginner in programming and struggling with this. Here's what I'm currently seeing: You are not getti ...

Having difficulty updating the state within a function

While working on developing a server-side pagination that mimics a static version, I have almost completed it. However, I have run into some issues that I am struggling to resolve. Here's how my code currently looks: const LiveIndex = (props) => { ...

Changing text content into objects in Protractor

I am facing an issue with a span tag that contains JSON text, which I need to convert into an object in Protractor for testing purposes. {"type":"msax-cc-error","value":[{"Code":22104,"Message":"Card holder is required"},{"Code":22058,"Message":"Card numb ...

Using the 'onended' audio event emitter in Angular 2 along with a local member of the Component

I'm looking for assistance on how to utilize audio.onended() in order to play the next song in a playlist. I can successfully add songs to the playlist and play them using the above method with an audioObject. However, when audio.onended triggers, I ...

The sticky navigation bar hack (implementing fixed positioning with jQuery)

Essentially, when the navigation bar (or any other element) reaches the top of the page or window, a class called "sticky" is added to the element and CSS styles it as fixed. This functionality acts like an IF statement - if the element is far from the top ...

What is the best way to send the index variable to an HTML element in Angular?

Is there a way to pass the index variable to construct HTML in the append() function? .directive('grid', ['$compile', function(compile) { return { restrict: "E", scope: { elements: '=' ...

"Encountering an error with Meteor while attempting to generate ObjectID due to an invalid hexadecimal

Recently, I've been working on updating data in the database while also inserting new information using jQuery (I know, I'm still learning). After this process, I need to be able to click on the data and display some user interface elements, whic ...

The AJAX feature allows for posting only the initial form

I'm currently facing an issue on my website where I have multiple forms for voting on various posts. Although I've successfully implemented AJAX for this functionality, it seems to work only with the first form. I understand that I need to make s ...

How come my audio element in HTML refuses to play once I adjust its volume setting?

I'm currently working through a React tutorial and I've encountered an issue with my component. I have implemented an audio HTML tag in the component, with its volume controlled by an input from another React component. However, despite setting u ...

modifying a record in MongoDB with the help of Mongoose

I need help with updating a collection in MongoDB using Mongoose. function check (db) { var hours = 60 * 60 * 1000 var threeHours = 3 * hours; var lastUpdated = null; db.collection("profile").find({userName: "Rick"}).toArray(function(er ...