Grouping by month and displaying them in two nested lists in Angular.js

I have a list of items. Each element contains a property date

. I want to group all items by month and display them in two nested lists.

Example

  • June 2015

    • Paragraph 1
    • Point 2
    • Point 3
  • May 2015

    • Item 4
    • Item 5
    • Item 6

and etc.


Is it possible to achieve this in Angular.js without using underlying data (i.e. through filters, etc.)?

I've tried the method described in this section: How can I group data using an Angular filter? but it messes up the order of the elements and I need to manually format the date to 'MMMM YYYY'

before calling groupBy

.

+3


source to share


1 answer


Looks pretty straight forward, just group the items by date and show:

var itemsGroupedByMonth = function (items) {
    var
        groups = [[], [], [], [], [], [], [], [], [], [], [], [],],
        itemGroupedByMonths = [];

    for (var i = 0; i < items.length; i++) {
      groups[items[i].date.getMonth()].push(items[i]);
    }
    for (var i = 0; i < groups.length; i++) {
      if (groups[i].length) {
        itemGroupedByMonths.push({
          month: monthLabels[i],
          items: groups[i]
        });

      }
    }
    return itemGroupedByMonths;
  };

      



Find a working example here: http://plnkr.co/edit/idvloFKoFvWGdBSGfMsX?p=preview

+2


source







All Articles