moniqueyj moniqueyj - 2 months ago 17
HTTP Question

I have sorting by Month function but somewhat I work only one time

I'm using javascript and angular to sort data.
I tried to filter my data by month.
It works first time and then somehow It doesn't work after then.
and data table disappear on the browser.
How can I make this filter button constantly as like it suppose to be.

Here's some parts of my files that related.

----- In 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 part of 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>




-------- this is my `component`(it works like `.directive` but somewhat
better way) 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;
}
};
});


Thanks!

Answer

the problem is in your filter function where you override $scope.lists with filtered list but never restore it to the original list:

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

I changed it to

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

where line

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

ensures that we have original list stored in $scope.unfilteredLists

also, you use unnecessary $q in your factory, just return $http.get, which is a promise by its self.

I created working plunker https://plnkr.co/edit/o6QVWfEi0WUBpPlsk3kV?p=preview