我有一个数组,我想在Angular.js中按日期订购:
<tr ng-repeat="er in vm.readerFeeds | orderBy:'-publishedDate'">
<td>{{er.publishedDate}}</td>
</tr>
列表没有正确排序。我认为日期格式是原因?
日期格式为:
Sat, 09 Nov 2013 04:26:55 -0800
答案 0 :(得分:6)
要使orderBy
正常工作,您需要在控制器中使用new Date(/**/)
对象包装字符串日期。
例如:
$scope.vm.readerFeeds = [
{
//.....
publishedDate: new Date(/*your string date*/);
},
{
//.....
publishedDate: new Date(/*your string date*/);
}
];
答案 1 :(得分:0)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://code.angularjs.org/angular-0.9.19.min.js" ng:autobind></script>
<title></title>
<script type="text/javascript">
function MainCOn() {
this.friends = [{
name: 'John',
phone: '555-1212',
age: 10,
date: '11/02/2015'
},
{
name: 'Mary',
phone: '555-9876',
age: 19,
date: '11/01/2015'
},
{
name: 'Mike',
phone: '555-4321',
age: 21,
date: '11/04/2015'
},
{
name: 'Adam',
phone: '555-5678',
age: 35,
date: '11/03/2015'
},
{
name: 'Julie',
phone: '555-8765',
age: 29,
date: '11/05/2015'
}];
}
MainCOn.prototype = {
sort: function (item) {
if (this.predicate == 'date') {
var DateInNumber = item.date;
var day = DateInNumber.split('/')[0];
var month = DateInNumber.split('/')[1];
var year = DateInNumber.split('/')[2];
var monthName = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
var dateInAlphabatical = day + ' ' + monthName[month - 1] + ' ' + year;
return new Date(dateInAlphabatical);
}
return item[this.predicate];
},
sortBy: function (field) {
if (this.predicate != field) {
this.predicate = field;
this.reverse = false;
console.log('f' + this.predicate + ' p' + this.reverse);
} else {
this.reverse = !this.reverse;
console.log('else' + this.reverse);
}
},
reverse: false
};
</script>
</head>
<body>
<div ng:controller="MainCOn">
<table>
<tr>
<th>
<a href ng:click="sortBy('name')">Name</a>
</th>
<th>
<a href ng:click="sortBy('phone')">Phone Number</a>
</th>
<th>
<a href ng:click="sortBy('age')">Age</a>
</th>
<th>
<a href ng:click="sortBy('date')">Date</a>
</th>
</tr>
<tr ng:repeat="friend in friends.$orderBy(sort, reverse)">
<td>
{{friend.name}}
</td>
<td>
{{friend.phone}}
</td>
<td>
{{friend.age}}
</td>
<td>
{{friend.date}}
</td>
</tr>
</table>
</div>
</body>
</html>