I am trying to groupBy
a date which is a JS date object. I want to group the data per day.
Any ideas how I can do this in a view?
$scope.data = {
messages: [
{
date: new Date(1432811030 * 1000),
message: 'Some text 01'
},
{
date: new Date(1432731600 * 1000),
message: 'Some text 02'
},
{
date: new Date(1432819703 * 1000),
message: 'Some text 03'
}
]
};
And in my view I use:
<div ng-repeat="(key, value) in data.messages | groupBy: 'date'">
<div>{{ key }}</div>
<div ng-repeat="message in value">
<div>{{ message.message }}</div>
</div>
</div>
I have this angular.filter
module included in mu project: https://github.com/a8m/angular-filter
Problem is that I now group per date/time instead of per day. Any idea how?
DEMO: http://plnkr.co/edit/djPMu4UH9t9BeGwBcUMI
Screenshot: https://www.dropbox.com/s/9z5t6nsp3x1266s/Screenshot%202015-05-28%2019.50.44.png?dl=0
HTML:
<body ng-app="myApp" ng-controller="myController">
<div ng-repeat="(key, value) in testData.messages">
<div>{{ key }}</div>
<div ng-repeat="message in value">
<div>{{ message }}</div>
</div>
</div>
</body>
JS:
var app = angular.module('myApp', []);
app.controller('myController', function($scope) {
$scope.data = {
messages: [
{
date: new Date(1432811030 * 1000),
message: 'Some text 01'
},
{
date: new Date(1432731600 * 1000),
message: 'Some text 02'
},
{
date: new Date(1432819703 * 1000),
message: 'Some text 03'
}
]
};
$scope.convertTo = function (arr, key, dayWise) {
var groups = {};
for (var i=0;l= arr.length, i<l;i++) {
if (dayWise) {
arr[i][key] = arr[i][key].toLocaleDateString();
}
else {
arr[i][key] = arr[i][key].toTimeString();
}
groups[arr[i][key]] = groups[arr[i][key]] || [];
groups[arr[i][key]].push(arr[i]);
}
return groups;
};
$scope.testData = {};
angular.copy($scope.data, $scope.testData);
$scope.testData.messages = $scope.convertTo($scope.testData.messages, 'date', true);
console.log($scope.testData)
});