我按月排序功能,但有点我只工作一次

问题描述:

我正在使用JavaScript和角度来排序数据。 我试图按月过滤我的数据。 它第一次工作,然后以某种方式后它不工作。 和数据表在浏览器上消失。 我怎样才能使这个过滤器按钮不断地像它想象的那样。我按月排序功能,但有点我只工作一次

这里是我的文件的相关部分。

----- 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; 
     } 
    }; 
    }); 

谢谢!

+0

建议你创建复制问题的演示。我们无法从所显示的内容中重现它。见[mcve] – charlietfl

问题是在你的过滤功能,你重写$ scope.lists用过滤列表,但从来没有将它恢复到原来的列表:

$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}`); 
}); 

我改成了

$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}`); 
    }); 
    }; 
}; 

在哪里行

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

确保th在我们有原始列表存储在$ scope.unfilteredLists

另外,您在您的工厂使用不必要的$ q,只需返回$ http.get,这是一个承诺的自我。

我创建工作plunker https://plnkr.co/edit/o6QVWfEi0WUBpPlsk3kV?p=preview

+0

感谢您的好评!并感谢你的工厂小费! – moniqueyj

+0

它运作得非常好:)有一个愉快的一天!!!!!!! – moniqueyj