Filtering data based on dates in AngularJS

I need to implement a data filter based on event date. The options for filtering include the current day, current month, and current year. Below is the current implementation:

function filterDate($scope) {
    var d = new Date();
    var curr_date = d.getDate();
    var curr_month = d.getMonth();
    var curr_year = d.getFullYear();

    $scope.dateToday = Date.parse(curr_month + "/" + curr_date + "/" + curr_year);
    $scope.dateRange = ""; 

    $scope.dataModels = [
    {age:5,name:'John Lennon',eventDate:"1390524400000"},
    {age:12,name:'Nick Young',eventDate:"1377500400000"},               
    {age:10,name:'Mike Johnson',eventDate:"1374044400000"},
    {age:15,name:'Lisa Leslie',eventDate:"1335942000000"}
    ];

    $scope.eventDateFilter = function(column) {
        if(column === 'today') {
            $scope.dateRange = $scope.dateToday;
        } else if (column === 'currentWeek') {
            //need logic
        } else if (column === 'currnetMonth') {
           //need logic        
        } else if (column === 'currnetYear') {
            //need logic            
        }else {
            $scope.dateRange = "";
        }
    }
}

Here's how the controller looks like:

<div ng:controller="filterDate">
Date Filter
    <ul class="inline">
        <li><a href ng-click="eventDateFilter('all')">All</a></li>
        <li><a href ng-click="eventDateFilter('today')">Today</a></li>
        <li><a href ng-click="eventDateFilter('pastWeek')">Past Week</a></li>
        <li><a href ng-click="eventDateFilter('pastMonth')">Past Month</a></li>
    </ul>
    <table class="table">
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Event Date</th>
        </tr>
        <tr ng:repeat="data in dataModels | filter:dateRange">
            <td>{{data.name}}</td>
            <td>{{data.age}}</td>
            <td>{{data.eventDate | date:medium}}</td>
        </tr>
    </table>    
</div>

You can view the complete code here : The code

Answer №1

Original Answer

Let me rephrase your query to ensure I address it accurately, as there seems to be some uncertainty:

You provided a list of objects with properties like

{age: <Number>, name: <String>, eventDate: <Timestamp>}
, and you wish to filter them based on the eventDate attribute. Specifically, you want to isolate objects within the current week.

To accomplish this, a slight adjustment in your Controller is necessary:

$scope.dateRanges = {
    all: {from: 0, to: Number.MAX_VALUE},
    // Functions getCurrent[Week,Month,Year]Range() will need to be defined by you,
    // This discussion (https://stackoverflow.com/questions/8381427/) provides insight
    week: getCurrentWeekRange(),
    month: getCurrentMonthRange(),
    year: getCurrentYearRange(),
};
$scope.currentDateRange = $scope.dateRanges.all; // set as the initial value
$scope.eventDateFilter = function(event) {
    return $scope.currentDateRange.from <= event.eventDate
        && event.eventDate <= $scope.currentDateRange.to;
});

Utilize the following approach in your template:

<ul>
    <li ng-click="currentDateRange = dateRanges.all">show all</li>
    <li ng-click="currentDateRange = dateRanges.week">show week</li>
    <li ng-click="currentDateRange = dateRanges.month">show month</li>
    <li ng-click="currentDateRange = dateRanges.year">show year</li>
</ul>
<table>
    <tr ng-repeat="data in dataModels | filter:eventDateFilter">
        <td>{{data.name}}</td>
        <td>{{data.age}}</td>
        <td>{{data.eventDate | date:medium}}</td>
    </tr>
</table>

An important distinction lies in changing the model upon navigation through ng-click, allowing Angular to update the view automatically.

This paradigm shift is crucial in Angular development, where the template reflects changes in the model without manual intervention, unlike traditional approaches involving jQuery or similar libraries.


Edit: getCurrentDayRange()

In response to comments about creating ranges (e.g., for the current day), refer to the method below inspired by this referenced solution.

function getCurrentDayRange() {
    // Return current day's start and end times
    return {
        from: new Date().setHours(0, 0, 0, 0), // Day begins at 00:00:00.000
        to: new Date().setHours(23, 59, 59, 999) // Day ends at 23:59:59.999
    };
}

Regarding when to invoke eventDateFilter: it is triggered automatically by the AngularJS digest loop, eliminating the need for manual execution. Review the Scope documentation for comprehensive insights.

Answer №2

If you want to simplify your date calculations, consider utilizing the power of moment.js library

function getTodayRange() {
    return {
        from: moment().startOf('day'),
        to: moment().endOf('day')
    };
} 
function getCurrentWeekRange() {
    return {
        from: moment().startOf('week'),
        to: moment().endOf('week') 
    };
};
function getCurrentMonthRange() {
    return {
        from: moment().startOf('month'),
        to: moment().endOf('month') 
    };
} 

function getCurrentYearRange() {
    return {
        from: moment().startOf('year'),
        to: moment().endOf('year') 
    };
}    

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

Efficiently communicating updates to clients after executing multiple HTTP requests simultaneously in RxJS

Objective: Execute multiple asynchronous HTTP requests simultaneously with RxJS and trigger a callback after each request is completed. For instance: fetchData() { Observable.forkJoin( this.http.get('/somethingOne.json').map((res:Re ...

Error message in the browser console: Uncaught TypeError - The function allSections.addEventListener is not recognized

Whenever I inspect my browser console, I keep encountering this error: Uncaught TypeError: allSections.addEventListener is not a function at PageTransitions (app.js:16:17) at app.js:33:1 I find it strange because my VS Code editor does not display any err ...

Passing data to an Angular directive

I am facing an issue while trying to pass information through a view in a directive. Despite binding the scope, I keep seeing the string value 'site._id' instead of the actual value. Below is the code for the directive: angular.module('app ...

Split total based on checkboxes toggled with JavaScript

I'm facing a challenge. I have a total sum of donations collected, for example, 10€. Additionally, there are various NGOs that one can select to donate to. Individuals have the option to toggle on/off which NGO's they wish to contribute toward ...

Incorporating a requirement into a function to ensure it is executed only under certain circumstances

I'm currently developing a text-based game using JavaScript that involves picking up a sword with the help of an in-game function. var takeSword = function() { if (currentRoom.hasSword) { $("<p>You picked up a sword.</p&g ...

Struggling with the functionality of Angular Material Layout Directives

Looking to implement the Child-Alignment feature in Angular Material but running into some issues. Details available here: https://material.angularjs.org/latest/layout/alignment Despite trying to import import { LayoutModule } from '@angular/cdk/l ...

What is the best way to display or conceal buttons when the textarea is in focus or out of focus, while still allowing them

Seeking help to include two buttons beneath the input box. One button is for saving the input in the textarea, while the other is for aborting. The buttons should only be visible when the input field is focused. An issue I am facing is that clicking on ...

What is the best way to use jQuery to update the color of an SVG shape?

Hello everyone! I'm excited to be a part of this community and looking forward to contributing in the future. But first, I could really use some assistance with what seems like a simple task! My focus has always been on web design, particularly HTML ...

Retrieve the radio button value from the HTML form

This website is designed to calculate ideal weight based on input data, but I am encountering an issue with the gender selection. The code seems to only recognize the first condition for female, while ignoring the else if condition for male. How can I fix ...

Designing a layout with one box on top and two beneath it, covering the entire page, can be achieved by following these steps

https://i.sstatic.net/A1eUh.png I am currently working on a project where I want to divide the screen into three sections. One section will cover half of the screen to display an image slider, and the remaining half will have two sections which is already ...

The absence of a defined camera function in Cordova is causing the issue

I recently added camera functionality to my ionic-angular app and encountered an error stating "Camera is not defined." This issue arises when I run the command ionic serve, but it doesn't occur when using ionic browser. The same error occurs when dep ...

What specific characteristic of TypeScript's number data type or the Math.ceil() function is responsible for this calculation mistake?

Currently, I am working on a function in Typescript that is supposed to generate a unique number each time it runs. However, there seems to be a problem with the arithmetic as the results are not always correct. Upon further examination of the code below, ...

React component stuck in endless loop due to Intersection Observer

My goal is to track the visibility of 3 elements and update state each time one of them becomes visible. Despite trying various methods like other libraries, useMemo, useCallback, refs, etc., I still face challenges with my latest code: Endless loop scenar ...

What is the most effective way to save and access British pound symbols?

Every so often, I face this issue where I end up resorting to a messy workaround. There must be a correct way to handle it though, as it's common to work with UK pound symbols. The dilemma is this: when the user inputs a UK pound symbol (£) into a t ...

When using the `Document.write()` method, an error is returned stating, "Uncaught TypeError: Cannot read property 'document' of null"

I am currently integrating Angular2 into a website as the front-end framework, and it will be displayed on another website using an iframe. When working with the HTTP post method, I am able to receive a JSON response. Here is the API Post method that retu ...

By setting `queue: false` when calling jQuery's `show()` method, you can

When looking at the code below, it is clear that even though showLoader is the first call, the loader does not appear immediately. This delay is due to the fact that heavyLifting function is blocking the UI thread. function onClick() { showLoader(); ...

Tips for invoking a function using ng-model together with the ng-model value

Within a div element, I have a text field where I am using ng-model to capture the value. I need to trigger a function for validation when a date is entered in the text field. How can I achieve this while still utilizing ng-model? Any suggestions on how to ...

Masked input fails to accurately capture data

When utilizing VueJS together with the Quasar framework. An issue arises when using a masked q-input, where the value becomes incorrect after a toggle. For instance, if we start with a default value of: officeNum: 654321, mobileNum: 12345678, Then our ...

Executing functions across modules in node.js

I need assistance with two of my modules: var client = require('./handlers/client.js'); var server = require('./handlers/server.js'); server.createClient() The client module: var client = function(){ console.log("New client"); ...

Encountering a syntax error while attempting to import modules from amCharts

Recently, I have been attempting to incorporate amcharts into my project using npm. After running the command npm install@amcharts/amcharts4, I noticed that all the necessary modules were now present in my node_modules folder and package.json file. Specifi ...