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?
The ng-repeat values can be filtered according to the ng-model in AngularJS by using the value of the input field as an expression in a filter. We can set the ng-model directive on an input field to filter ng-repeat values.
You can consider using transclusion inside a custom directive, to achieve the behavior you are looking for without using ng-repeat.
Definition and Usage. The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.
You can use $last variable within ng-repeat directive. Take a look at doc. Where computeCssClass is function of controller which takes sole argument and returns 'last' or null .
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With