我使用javascript和angular来排序数据。 我试图按月过滤我的数据。 它是第一次工作,然后以某种方式它在那之后不起作用。 和数据表在浏览器上消失。 如何使这个过滤器按钮不断变化,就像它想象的那样。
这是我的文件的某些部分。
----- 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 :(得分:0)
问题在于您的过滤器功能,您使用过滤列表覆盖 $ 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;
确保我们将原始列表存储在 $ scope.unfilteredLists
中另外,你在工厂里使用了不必要的$ q,只需返回$ http.get,这是自己的承诺。
我创建了工作的plunker https://plnkr.co/edit/o6QVWfEi0WUBpPlsk3kV?p=preview