Re: display an element only if a filter doesn't return some elements

7,829 views
Skip to first unread message

Mike Stelten

unread,
Jun 16, 2013, 1:38:28 AM6/16/13
to ang...@googlegroups.com
The plunkr link posted no longer works.  Anyone know how to make sure a filter function is only run once each time the query changes?

On Tuesday, 3 July 2012 10:20:15 UTC-5, Andy Joslin wrote:
Here is one way:
<p ng-show="(todos | filter:query).length==0">There are no todos for given query</p>

The downside of this way is you'll run the filter function an extra time, which isn't good for performance.  Although this is a super super simple filter function, so it won't be noticeable.

Another way would be to filter in your controller and make sure it only runs the filter function once each time the query changes: http://plunker.no.de/edit/WSeNoi?live=preview

This is a bit more trouble to code, but is more efficient if you have an intensive filter function.

John Duane

unread,
Nov 3, 2013, 2:58:45 PM11/3/13
to ang...@googlegroups.com
Here is another way that should not re-execute the filter function:

<input ng-model="query" name="query">
store the filter results in filteredData:
<ul>
  <li ng-repeat="todo in filteredData = (todos | filter:query">{{todo}})"</li>
</ul>
then check filteredData's length to conditionally show a warning:
<p ng-show="filteredData.length==0">There are no todos for given query</p>

Hope it helps,
John.

On Tuesday, July 3, 2012 8:24:46 AM UTC-6, Jakub Arnold wrote:
I have a list created via ng-repeat with a filter:query and I want to be able to show an element if there are no elements left by the filter.

Basically my idea would be something like this, where I assign a class based on the count of the displayed elements

<input ng-model="query" name="query">

<ul>
  <li ng-repeat="todo in todos | filter:query">{{todo}}</li>
</ul>

<p class="display-{{something like todos.length}}">There are no todos for given query</p>

The problem is, that .length doesn't get updated with the filter, and something like todos.count() doesn't work.

What is the proper way of doing this?

Alvaro Doune

unread,
Jun 12, 2014, 1:49:34 PM6/12/14
to ang...@googlegroups.com
Many thanks, that's exactly what I was looking for.

El martes, 3 de julio de 2012 13:43:06 UTC-3, Jakub Arnold escribió:
Thanks, that's exactly what I was looking for.

Lucas Ricoy

unread,
Aug 7, 2014, 7:45:51 PM8/7/14
to ang...@googlegroups.com
Thanks! I was able to work with that.

Darrius Taylor

unread,
Jul 15, 2015, 4:38:36 PM7/15/15
to ang...@googlegroups.com
Thanks John. I know this answer is like 2 years old but definitely appreciated.
Reply all
Reply to author
Forward
0 new messages