1

I'm building an event listing (teaching myself Angular) and I'm trying to conditionally insert a year and a month element between event listings when the year/month changes.

<body ng-controller="CalendarController">
 <div ng-repeat="event in events">
  <div ng-if="$first || year != prevYear ">
   {{event.date | date: 'yyyy'}}
  </div>
  <div>
   {{ event.name }}
  </div>
  <div>
   {{ event.date | date: 'shortTime'}}
  </div>
 </div>
</body>

Here if the element is the first it gets preceded by a year element (and the eventually the same for month) or if the year from the previous event is not the same as the current event.

(function(){
  var app = angular.module('a2Events', []);
  app.controller('CalendarController', function($scope, $http) {
    $http.get('../data.json')
         .success(function(data, status, headers, config) {
          angular.forEach(data, function(value, key) {
            value['date'] = Date.parse(value['date']);
          });
      $scope.events = data;
    })
    .error(function(data, status, headers, config) {
      console.log(status);
    });
  });
})();

Here I'm just replacing the date string with a date object, all pulled from a json file. The file is just a listing of events, in order by date. My assumption was I could pull the year and month separately from date objects (using $index) and just use the ngif for conditionally adding year/month elements where they are needed, but I can't seem to access the date object the way I'd need to for that. Does anyone have a suggestion for doing what I need, or an alternate method?

The output should be something like:
2015
July
event1
event2
August
event3
event4
2016
January
event5
etc

jshwlkr
  • 335
  • 6
  • 18
  • I believe this question is a duplicate of: http://stackoverflow.com/questions/26712458/angular-list-with-ng-repeat-with-date-as-divider – GPicazo Jun 30 '15 at 22:47
  • Wouldn't I still have to extract out the month and year though? – jshwlkr Jun 30 '15 at 22:59
  • Yes, you would. In the linked question, the original list is regrouped using the groupBy filter. However, it is grouped by full date (rather than year/month). So you have 2 options, either group the items on scope after they are fetched, or create a custom groupBy filter that does the date grouping only on year and month. I think grouping on scope is much easier, but would opt for a filter if you need to perform this grouping in several places in the app. – GPicazo Jun 30 '15 at 23:10

1 Answers1

0

I just cheated and did

ng-if="event.year != events[$index - 1].year"