My month sorting function is designed to work efficiently, although it seems to only be effective on the first

I am currently using a combination of JavaScript and Angular to sort through my data. Initially, I attempted to filter the data by month and it worked as expected the first time. However, for some reason, it stopped functioning properly afterwards, causing the data table to disappear from the browser. I am looking for a way to ensure that the filter button consistently functions as it should.

Below are snippets of the files related to this issue:

----- Inside my `controller`

   function CreateTableController($scope,$http, listsFactory){
   listsFactory.getLists().then(function(response){
      $scope.lists = response.data;
      console.log($scope.lists);
    }, function(error){
     console.error(error);
    });

   $scope.filter = function(year, month) {
     console.log('filtering');
     $scope.unfilteredLists = $scope.lists;
     $scope.lists = $scope.lists.filter((record) => {
       console.log(record);
       return record.date.includes(`${year}-${month}`);
     });
   };

----------- This is a section from my `html` files

      <section class="filteringBymonth">
          <input name="year" type="text" ng-model="date.year" >
          <input name="month" type="text" ng-model="date.month" >
          <button name="filter" ng-click="filter(date.year,  
           date.month)">Filter</button>
      </section>

  -------- Here is my `component` (similar to `.directive` but with improvements) and `factory` file, just in case

   sampleApp.component('createDataTable',{
     template: require('./create-data-table.html'),
     controller: 'CreateTableController',
     controllerAs:'createTableCtrl'
   });

   sampleApp.factory('listsFactory', function($q,$http){
     return {
     getLists: function(){
        var deferred = $q.defer(),
        httpPromise = $http.get('something.json');                                                
       httpPromise.then(function(response){
          deferred.resolve(response);
       }, function(error){
         console.error(error);
       });
        return deferred.promise;
       }
     };
   });

Thank you for your assistance!

Answer №1

There seems to be an issue in your filter function, where you are replacing $scope.lists with the filtered list but not restoring it back to the original list:

$scope.filter = function(year, month) {
 console.log('filtering');
 $scope.unfilteredLists = $scope.lists;
 // original list is being overwritten here
 $scope.lists = $scope.lists.filter((record) => {
   console.log(record);
   return record.date.includes(`${year}-${month}`);
 });

To fix this, I made the following changes:

$scope.filter = function(year, month) {
   console.log('filtering');
   // storing the original list
   $scope.unfilteredLists = $scope.unfilteredLists || $scope.lists;
   $scope.lists = $scope.unfilteredLists.filter((record) => {
     return record.date.includes(`${year}-${month}`);
   });
  };
};

The line:

$scope.unfilteredLists = $scope.unfilteredLists || $scope.lists;

ensures that the original list is saved in $scope.unfilteredLists.

Additionally, you are using unnecessary $q in your factory. Just return $http.get, as it is a promise itself.

I have created a functional Plunker example here: https://plnkr.co/edit/o6QVWfEi0WUBpPlsk3kV?p=preview

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

The color scheme detection feature for matching media is malfunctioning on Safari

As I strive to incorporate a Dark Mode feature based on the user's system preferences, I utilize the @media query prefers-color-scheme: dark. While this approach is effective, I also find it necessary to conduct additional checks using JavaScript. de ...

Managing numerous ajax forms within a single page

Upon receiving advice from the following inquiry Multiple forms in a page - loading error messages via ajax, I am endeavoring to incorporate multiple forms within one page. The goal is to insert error messages into the corresponding input div classes. I pr ...

Ways to showcase Material-UI Grid components without using cards

I initially used Material-UI grid items for spacing adjustments, but now they are displaying as cards. I would prefer them to be invisible like before, but the documentation doesn't provide a solution for this issue. Any assistance would be greatly ap ...

Is there a way for me to retrieve the variables saved within this array in JavaScript (vue.js)?

I'm currently working on a project involving the JavaScript Vue.js Framework. I've encountered an issue that I need help with, and I've included some code below to illustrate my problem. In the code, I have two variables in the data section ...

Establishing relationships with Sequelize between tables in different schemas

Currently, I am working on a project that involves using Sequelize and PostgreSQL as the database. In this project, I have implemented dynamic schema creation whenever a new user registers on the website. Specifically, I have a table called user_credentia ...

What is the best way to create a delay so that it only appears after 16 seconds have elapsed?

Is there a way to delay the appearance of the sliding box until 16 seconds have passed? <script type="text/javascript"> $(function() { $(window).scroll(function(){ var distanceTop = $('#last').offset().top - $(window).height(); ...

Customize ion-icon within a Tab button using ng-class in Ionic AngularJS

I'm struggling to update the icon on Tab from "ion-social-google-outline" to "ion-social-google" once it's clicked, but I haven't been able to crack the code... Because I need to navigate within an ion-slide-box, I can't utilize ion-ta ...

"Exploring ways to create and save content in a different root folder within a nodejs project using my

In the process of developing my npm module, I am faced with the task of creating or writing a file in either the root directory or a specific folder within the nodejs project that will be utilizing my module. This includes users who will be implementing my ...

Preventing the detection of a jshint "error"

When creating an object using the constructor X, I later add multiple methods in the file using X.prototype.method = function () {...}. Although technically an assignment statement, it behaves like a function declaration, which typically doesn't requi ...

Instructions on utilizing API call ( jssor_slider1.$GoTo(N))

Hi there, I could use some assistance with using the Api Call. I've been attempting to specify a slide using a command, but nothing seems to be working. Sorry for my inexperience, I appreciate your patience. Thank you! <script> function toSli ...

Could you assist me in retrieving information from an API request?

I can't seem to pinpoint my mistake, but I know it's there. After the user provides their state and city information and submits it, a fetch request is supposed to retrieve latitude and longitude values. These values are then used in another API ...

Issue with iPhone CSS displaying differently on mobile devices

The CSS design does not display correctly on iPhone devices in real-life testing, even though it appears fine on browsers with mobile view emulators. Interestingly, the design also looks great on Android phones but encounters issues specifically on iPhones ...

Having difficulty accessing the ::after element on Firefox when attempting to click

I've encountered an issue with my HTML and CSS code - it functions perfectly on Chrome, yet behaves differently on Firefox. button#groupToggle { background: 0 0; border: 1px solid #e6e6ed; color: #222; float: none; margin: 0 0 ...

When trying to use bootstrap modal buttons, they do not trigger with just a single click when

In my Angular code, I have implemented validation logic for when $locationChangeStart is fired. When this event occurs, I need to call event.preventDefault() to stop it and display a Bootstrap modal. However, I am encountering an issue where I have to clic ...

Vue.Js for a Single Page Application utilizing Two Data Sources

Currently, I am working on developing a Single Page Application using vue.js. My project consists of 2 bundles of pages stored in separate S3 buckets - one public and one private. The public bundle is meant to be accessible to all users, while the private ...

Discover the method for retrieving the upcoming song's duration with jplayer

Hey there, I have a question regarding the jPlayer music player. Currently, I am able to retrieve the duration of the current song using the following code snippet: $("#jquery_jplayer_1").data("jPlayer").status.duration; However, I now want to obtain t ...

Alter the div's HTML content once the Ajax operation is completed

I have a div element that looks like this: <div class="progress" id="progress-bar"></div> I am using the following JavaScript code along with an ajax call to retrieve some data. The data returned is 0, however, the content is not being added ...

What is preventing targeting a class in React?

I'm having trouble targeting className in react. I attempted to target it using div className="navbar"> and .navbar { align-items: center; } but it's not working. div{ display: block; background-color: rgb(211, 57, 57); ...

Can I use jqPlot to create a separate division for the legend?

Is it feasible to move the legend to a distinct div using jqPlot? legend: { show: true, placement: 'outside', fontSize: '11px', location: 'n' } ...

I'm encountering an issue where I receive the error `Cannot read property 'map' of undefined` while attempting to integrate the backend with React. What could be causing this error and how

I'm currently learning React and I've been using a tutorial here to connect my database to the front end of my React application. Unfortunately, every time I try running 'npm start' at 'localhost:3000' in express-react/backend ...