尝试为列表创建自定义角度过滤器。我也使用下划线:
app.filter('dateRangefilter', function($scope,_) {
return function(input) {
console.log('rangefilter');
_.filter($scope.data, function(row) {
return row.date >= '01/01/2000' && row.date <= '01/08/2020'
});
}
});
HTML:
<ul>
<li ng-repeat="item in data | dateRangefilter ">
{{item.name}}
</li>
</ul>
但是我收到了错误:
Error: [$injector:unpr] http://errors.angularjs.org/1.3.0-`beta.14/$injector/unpr?p0=<!-- ngRepeat: item in data | dateRangefilter -->copeProvider%20%3C-%20%24scope%20%3C-%dateRangefilterFilter`
如何通过daterange过滤数据?在这种情况下,在1/1/2000和1/8/2020之间?
答案 0 :(得分:0)
一种解决方案是使用$scope
定义的方法。见http://plnkr.co/edit/FBcfAZQ9QMdQiWdEsjMk?p=preview
HTML:
<ul>
<li ng-repeat="item in data | filter:dateRangefilter ">
{{item.name}}
</li>
</ul>
JavaScript的:
$scope.dateRangefilter = function(input) {
console.log(input);
return input.date >= '01/01/2000' && input.date <= '01/08/2020'
}
答案 1 :(得分:0)
问题是filter
的第二个参数应该是空函数。删除它,因为你真的不需要$scope
和_
(你已经拥有它们)。并修改以实现此目的:
app.filter('dateRangefilter', function() {
return function(input) {
return _.filter(input, function (d) {
return Date.parse(d.date) >= Date.parse('01/01/2000') && Date.parse(d.date) <= Date.parse('01/08/2020');
});
}
});
修改要点:
_.filter
。答案 2 :(得分:0)
几个问题:
在您的下划线模型中,您没有完成注入$window
。您还必须将它传递给函数本身:
underscore.factory('_', ['$window', function() {})
需要转向:
underscore.factory('_', ['$window', function($window) {})
您无法将日期比较为字符串。这是最后的功能:
app.filter('dateRangefilter', function(_) { // don't need $scope. It's irrelevant for a filter
return function(input) {
console.log('rangefilter');
return _.filter(input, function(row) { // needed to return this as well
var date = new Date(row.date);
var from = new Date('01/01/2000');
var to = new Date('01/08/2020');
return date >= from && date <= to; // dates can be compared properly
});
}
});