范围中匹配日期值的自定义ng筛选器

Custom ng-filter for matching date value in scope

本文关键字:自定义 ng 筛选 日期 范围      更新时间:2024-04-11

我正在尝试创建一个过滤器,该过滤器将根据日期过滤ng repeat中的项目。例如,在div标题"today"中,仅显示在每个items date属性中设置了today日期的items。我希望最终在标记中得到这样的东西:

<li class="{{todo.category}}" ng-repeat="todo in todos | taskDate : today">
    {{todo.title}}
</li>

todo结构示例:(日期是通过AngularUI引导程序指令生成的,因此不是100%的格式化方式。)

$scope.todos = [
{name : 'Complete 5 tasks',
category: 'Life',
date: ''}
]

我目前拥有的方法和过滤器如下:

Date.prototype.sameDay = function(d) {
    return this.getFullYear() === d.getFullYear() && this.getDate() === d.getDate() && this.getMonth() === d.getMonth();
};

app.filter("taskDate", function() {
    return function(input, date) {
        var todaysDate = new Date();
        var filtered = [];
        angular.forEach(input, function(todo, index) {
            if (todo.date instanceof Date) {
                if (todo.date.sameDay(todaysDate)) {
                    filtered.push(todo);
                }
            } else if (todo.date == date) {
                // filtered.push(todo);
            }
        });
        return filtered;
    };
});

当我使用以下过滤器

|taskDate
时,这适用于显示具有今天日期的项目,但我根本不知道如何将其扩展到显示明天等。

编辑:设法获得了一个适用于今天的过滤器,但不适用于其他日期

我认为您可以使用Angular的原生过滤器来帮助:

 <li class="{{todo.category}}" ng-repeat="todo in todos | filter:todoFilter('today')">

$scope.todoFilter= function(date) {
    return function(todo) {
        if(date==='today' && todo.date=== $scope.todaysDate)){
            return true;
        }
    }
}

Fiddle 示例