Filtering an ng-repeat list based on a sub-object property

Elise picture Elise · Jul 7, 2013 · Viewed 39.6k times · Source

jsfiddle http://jsfiddle.net/KfSBq/

By sub-object I mean that the objects I am displaying with ng-repeat all contain a list of objects within themselves, and I am looking to filter based on the property of one of those sub-objects.

This alone was quite straightforward to do. I have an object of dailies, each containing a date and an entries list of objects:

function Ctrl($scope) {
    $scope.dailies = [{date: new Date('07/07/2013'), 
                       entries: [{category: 'A', note:'Lorem ipsum'}, 
                                 {category: 'B', note: 'Lorem ipsum'}]},
                      {date: new Date('05/02/2013'), 
                       entries: [{category: 'A', note: 'Lorem ipsum'}]}];
}

I display them, filtering by category:

<div ng-controller="Ctrl">
        <div class="daily" ng-repeat="daily in dailies | orderBy:'-date' ">
            {{ daily.date | date:'dd/MM/y' }}
            <div class="entry" ng-repeat="entry in daily.entries | filter:{ category: 'B'} ">
                <span>{{ entry.category }}</span>, <span>{{ entry.note }}</span>
            </div>
        </div>
    </div>

My issue here is that the daily objects that now contain no entries at all are still displayed. How do I achieve a situation where, if the filtering makes the entries list of a daily empty, that daily is not displayed either?

Answer

Stewie picture Stewie · Jul 7, 2013

You are allowed to create new scope members inside the expressions.

This lets you assign a filtered list to a new variable, which can be used throughout the local scope. With that, you can pass the length of the filtered list to ng-show:

<body ng-app>
  <div ng-controller="Ctrl">
    <div class="daily" 
      ng-repeat="daily in dailies | orderBy:'-date' " 
      ng-show="filteredEntries.length"
    >
      {{ daily.date | date:'dd/MM/y' }}
      <div class="entry" 
        ng-repeat="entry in filteredEntries = (daily.entries | filter:{ category: 'B'})"
      >
        <span>{{ entry.category }}</span>, <span>{{ entry.note }}</span>
      </div>
    </div>
  </div>
</body>

FIDDLE

Btw, nicely put question!