use*_*646 1 javascript angularjs
所以我使用ng-repeat列出一些关于事件的信息,其中一个是日期字段.我想过滤日期,例如,能够在接下来的30天内显示事件.我不确定要采取什么方向来实现这一目标.
<table>
<tr>
<th>Title</th>
<th>Description</th>
<th>Start Time</th>
</tr>
<tr ng-repeat="eventData in eventListData | orderBy:'+StartDateTime'">
<td>{{eventData.Title}}</td>
<td>{{eventData.Description}}</td>
<td>{{eventData.StartDateTime|date:'d MMM yyyy'}}</td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
首先,orderBy的语法是错误的.它应该是"orderBy:'+ StartDateTime'",其中+/-控制asc/desc方向,而'StartDateTime'(mind单引号)是要从中拔出的字段.
使用StartDate的时间戳&do> now - <now + 30days,然后你有2个选项:
我更喜欢第二个选项,我觉得它更符合角度的精神,并允许更加动态的数据混乱.我在这里举了一个例子
var app = angular.module('app', []);
// filter array by @field {String}
// return items from today to @days {Number} from now
// eg: events | upComing:'StartDateTime':30
app.filter('upComing', function(){
return function(items, field, days){
var timeStart = Date.now();
var timeEnd = Date.now() + (days * 86400000); // 1 day in ms
return items.filter(function(item){
return (item[field] > timeStart && item[field] < timeEnd);
});
};
});
app.controller('ctrl', function($scope){
// demo data, StartDateTime should be numbers in your data
$scope.eventListData = [
{
Title:'Event 1 (last in 30 dys)',
Description:'A cool Event',
StartDateTime: Date.now() + (86400000 * 5) // in 5 days
},
{
Title:'Event 2 (next)',
Description:'A cool Event',
StartDateTime: Date.now() + 86400000 // in a day
},
{
Title:'Event 3 (next next)',
Description:'A cool Event',
StartDateTime: Date.now() + (86400000 * 2) // in 2 days
},
{
Title:'Too-far-away Event',
Description:'A cool Event',
StartDateTime: Date.now() + (86400000 * 40) // in 40 days
},
{
Title:'Already-happend Event',
Description:'A cool Event',
StartDateTime: Date.now() - (86400000 * 2) // 2 days ago
}
];
});
Run Code Online (Sandbox Code Playgroud)
这是HTML:
<html ng-app="app">
<head>
<meta charset=utf-8 />
<title>Angular Date Filter</title>
</head>
<body ng-controller="ctrl">
<table>
<tr>
<th>Title</th>
<th>Description</th>
<th>Start Time</th>
</tr>
<tr ng-repeat="eventData in eventListData | upComing:'StartDateTime':30 | orderBy:'+StartDateTime'">
<td>{{eventData.Title}}</td>
<td>{{eventData.Description}}</td>
<td>{{eventData.StartDateTime|date:'d MMM yyyy'}}</td>
</tr>
</table>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)