Implementing date range filtering in AngularJS model using filters

Within my view, I have the following:

<tr dir-paginate="post in posts |orderBy:propertyName:reverse | filter: searchPost | itemsPerPage: pageSize">
<td>
        {{post.title}}
</td>
<td>
        {{post.content}}
</td>
<td>
        {{post.dateOfCreation | date:"medium"}}
</td>
</tr>

Furthermore, I have implemented filtering across all fields:

     <div>
        <input type="text" placeholder="Find by title..." ng-model="searchPost.title" />
    <div>
    <div>
        <input type="text" placeholder="Find by content..." ng-model="searchPost.content" />
    </div>

    <div>
        <input type="text" placeholder="Find by date..." ng-model="searchPost.dateOfCreation" />
    </div>

However, the date only filters correctly when entered in the format: yyyy-mm-dd in the textbox; limited to a single date. I aim to allow users to select date ranges and display these values, yet I struggle to integrate this functionality with my existing searchPost filter... I am utilizing angular-datepicker:

<input date-range-picker class="form-control date-picker" type="text" ng-model="someDate" options = "{locale: {format: 'YYYY-MM-DD'}}"/>

   $scope.someDate = { startDate: null, endDate: null };

The datepicker library in use is: Angular Daterangepicker

Answer №1

To achieve this, you will have to develop a customized filter.

This custom filter will be responsible for validating whether the post was created within the specified date range.

Ultimately, the implementation will resemble the following code snippet:

// Initialize the filter
var app = angular.module('testFilters', []);

app.controller('postsCtrl', ['$scope', function($scope){
  $scope.posts = [
    {title: 'test 2010', dateOfCreation: new Date(2010, 1, 1)},
    {title: 'test 2012', dateOfCreation: new Date(2012, 1, 1)},
    {title: 'test 2014', dateOfCreation: new Date(2014, 1, 1)},
    {title: 'test 2016', dateOfCreation: new Date(2016, 1, 1)}
  ];

  $scope.searchPost = {title: 'test', date: {startDate: new Date(2011, 1, 1), endDate: new Date(2015, 1, 1) } };
}]);

app.filter('postFilter', function() {

  return function(input, post) {

    var out = [];

    angular.forEach(input, function(p) {
      var filtered = true;

      if(post.title && p.title.indexOf(post.title) < 0){
        filtered = false;
      }

      if(post.content && p.content.indexOf(post.content) < 0){
        filtered = false;
      }

      if(post.date && post.date.startDate && post.date.endDate){
        if(p.dateOfCreation < post.date.startDate || p.dateOfCreation > post.date.endDate){
          filtered = false
        }
      }

      if(filtered){
        out.push(p);
      }
    });

    return out;
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="testFilters" ng-controller="postsCtrl">
  <h3>unfiltered posts:</h3>
  <div ng-repeat="post in posts">
    ----------------------------------------------------<br>
    Title: {{post.title}}<br>
    Content: {{post.content}}<br>
    Created: {{post.dateOfCreation | date:'MM/dd/yyyy'}}<br>
  </div>
  <hr>
  <br>
  <h3>filtering post:</h3>
  <div>
    Title: {{searchPost.title}}<br>
    Content: {{searchPost.content}}<br>
    Range: {{searchPost.date.startDate | date:'MM/dd/yyyy'}} - {{searchPost.date.endDate| date:'MM/dd/yyyy'}}<br>
  </div>
  <hr>
  <br>
  <h3>filtered posts:</h3>
  <div ng-repeat="post in posts | postFilter:searchPost">
    ----------------------------------------------------<br>
    Title: {{post.title}}<br>
    Content: {{post.content}}<br>
    Created: {{post.dateOfCreation | date:'MM/dd/yyyy'}}<br>
  </div>
</div>

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

What is the best way to have my sliding panel automatically close when I click outside of it?

I have created a sleek sliding navigation panel for my website that appears when the screen width is reduced. Although I am satisfied with how it functions currently, I would like the panel to close when the user clicks/taps outside of it. What adjustments ...

Utilizing ElementRef in Ionic to load map into ngSwitch child scope

Is there a way to access a ngSwitchCase view using @ViewChild and ElementRef to load a Google map in an Ionic 3 app? I am aware that the ngSwitch creates its own scope, but is there a way to load the map from Google into the #map id="map" div within the ma ...

Can you explain the process of retrieving API information from a component directory with Next.js?

In the components folder, I have created a reusable component that displays user details for those who log into the system in the header section. Currently, I am attempting to utilize getInitialProps with isomorphic-unfetch. static async getInitialProps( ...

Is there a way in React to specify which properties to pass (and when to pass them) to child components based on the properties of the parent component?

In this hypothetical scenario, there are 4 components already in place: MainComponent1, MainComponent2, IntermediateComponent, and ChildComponent. Both MainComponent1 and MainComponent2 can utilize IntermediateComponent as their child component, while Chil ...

Choose particular spreadsheets from the office software

My workbook contains sheets that may have the title "PL -Flat" or simply "FLAT" I currently have code specifically for the "PL -Flat" sheets, but I want to use an if statement so I can choose between either sheet since the rest of the code is identical fo ...

The pagination in React using React Query will only trigger a re-render when the window is in

Currently, I am utilizing React-Query with React and have encountered an issue with pagination. The component only renders when the window gains focus. This behavior is demonstrated in the video link below, https://i.sstatic.net/hIkFp.gif The video showc ...

Iterating through children of the target element using the .each() method in jQuery

Currently, I am looping through the elements and extracting the src attribute from the child element. This is the snippet of HTML code that I am working with: <noscript data-alt="super awesome"> <img src="http://farm9.staticflickr.com/8235/85 ...

A step-by-step guide on incorporating box-shadow for the jackColor in the Switchery Plugin

I am looking to add a box shadow to my iOS7 style switches for checkboxes when they are checked. Here is the code I have so far: var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch')); elems.forEach(function (html) { va ...

Regarding passing input into a JavaScript class method that is exported through the exports keyword

The inquiry at hand relates to ExtendScript code, however, I believe it should be independent of any specific javascript implementation. If we have the following in a JS library file (base64.js) exports.encode64 = encoder('+/'); //... function ...

Tips for incorporating a Forgot/Reset password option into your #Firebase platform

In the project I'm working on, I am utilizing #AngularFire2. My goal is to incorporate a Reset / Forgot password link into the login page. Does anyone have suggestions on how to accomplish this task? I'm looking to get some insights from #AskFi ...

Animate my banner images only after they have fully loaded using Jquery

I recently came across a banner image slideshow in jQuery, but it seems to be animating even before the images are fully loaded. This results in the slideshow displaying image descriptions without the actual images themselves. Can anyone help me modify th ...

how to use jquery to indicate that a checkbox is selected

click here to see the image $(document).ready(function() { $('.editbtn').on('click', function(){ $('#editmodal').modal('show'); $tr=$(this).closest('tr'); var da ...

Having a tough time getting Storybook up and running

Hey there, I'm new to exploring React and I decided to give Storybook a try. Unfortunately, I encountered an error when attempting to run Storybook. I attempted to resolve the issue by updating with npm update, suspecting there may be dependency confl ...

Include certain tags to the content within the text apart from using bbcode tags

I need help with a project involving a BBCODE editor that can switch between a WYSIWYG editor and a code editor. The visual editor is designed with a drag-and-drop block system for elements like pictures and text. In the visual editor, when a user drags ...

(Enhancing Angular) Capture HttpResponse errors and seamlessly proceed with the Observable

There's a dropdown text box with type-ahead search functionality. Valid item names prompt the expected list of items in the drop-down menu, while invalid entries trigger a 400 error response from the API. This error is caught by the HttpErrorIntercept ...

Is there a way to turn off the highlights feature on MapHilight?

I am currently facing a challenge that has me stumped, and I am hoping you can provide some guidance. I'm working on a page located at: Here's the issue: I am focusing solely on the states of Washington and Idaho at the moment, and I want users ...

Preventing line breaks (endline) from PHP variable when passing to JavaScript

Check out my code snippet below: <td onclick="openFile('<?php echo htmlentities ($row['name'])?>',' <?php echo htmlentities ($row['content'])?>')"> <a href="#nf" dat ...

Guide on accessing APIs for individual elements in an array

Currently utilizing Next.js / React.js and making use of this API to retrieve information about a specific country. Within the response, there exists an array called borders, as shown below: borders: [ "CAN", "MEX", ], There is ...

Limited access textbox

Is there a way to create a text-box in AngularJS/HTML that is partially readonly? For instance, having the default value as "+91" and making it readonly while allowing users to enter additional values afterwards? ...

I'm experimenting with crafting a new color scheme using MUI, which will dynamically alter the background color of my card based on the API

I am attempting to create a function that will change the colors based on the type of Pokemon. However, I'm not sure how to go about it. Any suggestions or ideas!? Check out where I'm brainstorming this logic [This is where the color palette sh ...