Sorting a date in a simple grid table using AngularJS

I'm looking for a way to have a button that, when clicked, will sort a table by today's date in angularjs. This is the view page in my Angular project.

 <div class="form-inline has-feedback filter-header">
      <input type="text" class="form-control" placeholder="Search" ng-model="search.$" />
      <!-- <i class="glyphicon glyphicon-search form-control-feedback"></i> -->
      <button class="btn btn-default btn-sm" ng-click="hideFilter=!hideFilter">Advanced Search</button>
              </div>

        <a class="btn btn-default btn-sm pull-right" href="/#/add">Add New</a>
      </div> <!-- Grid filter ends -->

      <table class="table table-striped table-condensed table-responsive table-hover">
        <thead class="data-grid-header">
          <!-- table header -->
          <tr>
            <th>
              <span class="fa fa-th-large"></span>&nbsp;&nbsp;
              <a href="" ng-click="orderByField='title'; reverseSort = !reverseSort">Title</a>
            </th>
            <th class="hidden-xs">
              <span class="fa fa-calendar"></span>&nbsp;&nbsp;
              <a href="" ng-click="orderByField='startDate'; reverseSort = !reverseSort">Schedule Date</a>
            </th>
          </tr>

          <!-- table filter -->
          <tr ng-hide="hideFilter">
            <th><span ng-hide="hideFilter"><input type="text" ng-model="search.title"></span></th>
           </tr>      

        </thead>

        <tbody class="data-grid-data">
          <tr ng-repeat="visit in visitsList | filter: dateRange | filter: search |orderBy:orderByField:reverseSort">
            <td>{{visit.title}}</td>
            <td>{{visit.startDate | date:medium}}
         </tr>
       </tbody>
      </table>

I need help figuring out how to set up the controller to sort by the current date. Any assistance would be greatly appreciated. Thanks in advance.

Answer №1

If you want to filter the data in a table for today's date, you can create a function in your controller to achieve this.

$scope.filterDates = function() {
    //Get the current date.
    var currentDate = $filter('date')(new Date(), "MM/dd/yyyy");
    $scope.users.forEach(function(user) {
        //Convert dates to currentDate format for comparison.
        user.previousLogin = $filter('date')(user.previousLogin, "MM/dd/yyyy");
    });
    //Filter and update the users list.
    $scope.filteredUsers = $filter('filter')($scope.users, {previousLogin: currentDate});
}

After defining the function, you can call it using ng-click from your button.

Check out the Fiddle for an example: https://jsfiddle.net/npwug6xd/

Answer №2

If you want to arrange the rows based on their start date in ascending order, you can use the following code snippet:

<tr ng-repeat="visit in visitsList | orderBy: 'startDate'">
    <td>{{visit.name}}</td>
    <td>{{visit.startDate | date:medium}}
</tr>

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

ng-model does not function properly with ng-repeat in a dropdown menu

I am trying to display images in an option list using ng-repeat because I couldn't achieve it with ng-options. However, I am facing an issue where I am unable to retrieve the selected value from ng-change. It seems like ng-model is not working as expe ...

Error: When executing the npm run build command, I encountered a TypeError stating that Ajv is not a

I keep encountering an issue whenever I try to execute npm run build error: /node_modules/mini-css-extract-plugin/node_modules/schema-utils/dist/validate.js:66 const ajv = new Ajv({ ^ TypeError: Ajv is not a constructor at Object.<anon ...

What is the proper way to utilize "three.module.js"?

I am currently learning how to utilize modules and decided to start with a simple example. However, I encountered an issue where the script does not want to run. I must be missing something crucial, but I can't seem to figure out what it is. I have tr ...

Question about Looping Concept

var answer = ""; var correct = "4"; var question = "What is 2 * 2?"; for(i = 2; i < 5; i++) { answer = prompt(question, "0"); if (answer == correct) { alert("Your answer is correct!"); break; } } Before the break command is ...

Vue.js object formatting with whitespace

Unfortunately, I am faced with the challenge of working with an object that contains labels with spaces. To iterate through the object, I have been using the following code: v-for="index in $data['wins Lane 1'].player2.pts" The issue is that " ...

Tips for preventing the need to create a function within a loop

Currently, I am in the process of collecting data through REST calls. I have created a function that accesses a "directory" endpoint to retrieve a list of individuals. While I can easily obtain details about their children, I need to make individual AP ...

Error message: The function particle.subSelf() is not defined

I'm attempting to assign velocity and an origin to a particle using threes, but I'm having trouble adding the origin. function getOrigin() { return new THREE.Vector3(Weapon.vehicle.position.x, Weapon.vehicle.position.y, Weapon.vehicle.posit ...

What is the method for adding a default endpoint to Angular $http requests?

In my Angular application, I have a process where variables are retrieved from an environment file and then updated using Grunt. Upon completion of the grunt task, a specific variable is set in environment.js as follows: var envBaseUrl = 'https://live ...

What are the recommended methods or examples for implementing a scheduling calendar using JavaScript?

Here's a question that may be open to interpretation, and a red warning banner suggests it might be closed, but I'm not sure where else to turn for answers. I need an extremely lightweight display-only scheduling calendar for my application. Ess ...

When the mouse leaves, the background image will revert back to its original setting

https://i.stack.imgur.com/Ojd0Q.pngI need assistance in reverting a div's background image back to its default state using the onmouseleave method. Below is the HTML and JS code I have been working on: <script type="text/javascript"> functi ...

Activate and deactivate animation using one button with jQuery

Looking for a solution using Jquery. Can you animate an element when clicking a button and then stop the animation with the same button? Here is an example code snippet in JavaScript: $('<div>').css({ 'width':'200 ...

User-Preferred Dark Mode Toggle Using Material-UI and Fallback Option

I am working on implementing a toggle for "dark mode" that is functioning well. However, I want the initial state to reflect the user's dark/light preference. The problem is that prefersDarkMode seems to be set to false when the page loads. It only c ...

Error: The function referenced is not defined when the page loads

Trying to incorporate two different script tags in a single HTML page has been quite a task for me. The first script tag contains the location of a JS file that I need to use for a specific function, while the second script tag is where I have written anot ...

How to integrate angular-ui-bootstrap with webpack

I'm attempting to integrate https://github.com/angular-ui/bootstrap with Webpack: import angular from 'angular'; import uiRouter from 'angular-ui-router'; import createComponent from './create.component'; import tabs fro ...

After being awaited recursively, the resolved promise does not perform any actions

When working with the Twitter API, I need to make recursive method calls to retrieve tweets since each request only returns a maximum of 100 tweets. The process is straightforward: Call the function and await it Make an HTTP request and await that If the ...

Tips for managing a list of elements using keyboard input

https://i.sstatic.net/PtlmF.png https://stackblitz.com/edit/react-o1ra7c When the user performs a search, they can use arrow keys on the keyboard to navigate through the results. <div> <input onChange={ha ...

Explore accessing a PHP array with multiple dimensions using Jquery Ajax

I have a PHP script that runs a SQL query on my MSSQL Server instance and returns a good result. Now, I'm attempting to manipulate the result using $.ajax in jQuery, but it seems that accessing fields in an object table via "Object.field_name" is not ...

Choose Your Date of Birth from the Drop-Down Menu with ng-options

I've been working on creating a dropdown for Date of Birth using ng-options. I've managed to set it up for day and month, but I'm encountering an issue with the year dropdown. The problem is that the years are displayed in reverse order, sta ...

This function is designed to only work under specific conditions

Looking for assistance with a function that takes an item ID as input and changes its border when pressed. The goal is to increase the border width by 2px when there is no border, and remove the border completely when pressed again. Currently, only the f ...

The function RegisterClientScriptInclude seems to be malfunctioning inexplicably

I've been struggling for over 2 days trying various solutions and searching online, but I can't seem to get RegisterClientScriptInclude to function properly like everyone else. For starters, I am using .NET 3.5 Ajax and incorporating javascript ...