Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

angularjs - ng-repeat groupBy date field per day

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...