Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Drew Templeton
Drew Templeton
6,509 Points

Returning repeated objects only if unique in Angular's ng-repeat

I am using Angular to iterate through some events from a JSON file. All is well except I am trying to show repeated event.month only once in the ng-repeat. The event.month returns the month and the day (ie October 28th) and the event.day returns the day of the week (ie Tuesday)

If there are 20 events under October 28th, I only want the first October 28th to show up in the view. I've tried a few different custom filters but can't seem to get it right.

I've tried picking apart the unique filter from https://github.com/a8m/angular-filter but with no luck. The unique filter works, but it omits the entire object and I just want it to omit the date if it's already returned and to only show for the first date.

Any help would be greatly appreciated!

I have created a CodePen as well - http://codepen.io/drewbietron/pen/qLBit

Here is a dummied down version of what I'm working with so fat with css and the other filters I have omitted.

<ul ng-repeat="event in events">

    <span>
    {{event.day}}
    {{event.month}}
    </span>

    <li>

        <span>{{event.time}}</span>

        <h2>{{event.instructor}}</h2>
        <p>{{event.info}}</p>

    </li>

</ul>

1 Answer

Jack Choi
Jack Choi
11,420 Points

I've forked your page and hopefully this is what you wanted: http://codepen.io/anon/pen/aLeik

I made two changes:

  1. the output of the sorted events had to be stored so the $index values work properly:

    <ul ng-repeat="event in sorted_events = (events | orderBy: 'datetime')">
    
  2. for the area you wanted the content to hide, I added a conditional that checked against the previous event's month:

    <div class="date" ng-show="event.month != sorted_events[$index - 1].month">
    

Hope that helps and let me know if you require any more information!