I have an array which I want to order by date in Angular.js:
{{er.pu
-
To make to orderBy
to work you need wrap string date with object of new Date(/**/)
in controller.
For example:
$scope.vm.readerFeeds = [
{
//.....
publishedDate: new Date(/*your string date*/);
},
{
//.....
publishedDate: new Date(/*your string date*/);
}
];
讨论(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>
讨论(0)
- 热议问题