I have a table with a column for month and year. I need to sort the dates by year. Can someone please help me with this? You can view the code in the provided fiddle.
In my case, the date format is "MMMM yyyy". For example, if I have "August 2016", "September 2015", and "January 2018", I want to sort them based on the year to get "September 2015", "August 2016", and "January 2018".
How can I achieve this in angularjs?
var app = angular.module('app', [])
.controller('appController', appController);
appController.$inject = ['$scope', '$window'];
function appController($scope, $window) {
$scope.title = "date sorting example";
$scope.sortType = "name";
$scope.sortReverse = true;
var dateA = new Date("02/06/2016");
dateA.setDate(dateA.getDate() + 2);
var dateB = new Date("07/06/2017");
dateB.setDate(dateB.getDate() + 4);
var dateC = new Date("08/06/2016");
dateC.setDate(dateC.getDate() + 7);
var dateD = new Date("04/06/2018");
dateD.setDate(dateD.getDate() + 20);
$scope.allItems = [{
date: dateA,
name: "A"
}, {
date: dateB,
name: "B"
}, {
date: dateC,
name: "C"
}, {
date: dateD,
name: "D"
}];
};
<div ng-controller="appController">
<h1>This is my {{title}}</h1>
<table class="table table-striped">
<thead>
<td data-ng-click="sortType = name; sortReverse = !sortReverse;">
Date
</td>
<td data-ng-click="sortType = name; sortReverse = !sortReverse;">
Name
</td>
</thead>
<tbody>
<tr ng-repeat="item in allItems">
<td>{{item.date | date:"MMMM yyyy"}}</td>
<td>{{item.name}}</td>
</tr>
</tbody>
</table>
</div>