Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show a message when filter returns nothing in ng-repeat - AngularJS

I would like to show one div(message) when no items returned on filter(ng-repeat).

Filter is happening based on select box (ng-model). And there are no results for some select options, at that time user should be able to read a message at same place. Can I use ng-show/hide here? How?

Thanks,

like image 456
shaik Avatar asked Feb 03 '14 10:02

shaik


3 Answers

You can also save your filtered array in a variable and then use that variable inside the ng-show expression:

<select ng-model="shade" ng-options="shade for shade in shades"></select><br>
<ul>
    <li ng-repeat="c in filteredColors = (colors | filter:shade)">{{c.name}}</li>
</ul>
<div ng-show="!filteredColors.length">No colors available</div>

You can see it in action in this plunker.

like image 133
muenchdo Avatar answered Nov 10 '22 02:11

muenchdo


You can get the size of array returned by filter using something like

{{(data|filter:query).length}}

You can use this expression for ng-show expression. I am not sure how performant would it be.

like image 43
Chandermani Avatar answered Nov 10 '22 02:11

Chandermani


There's a simpler solution using just the standard syntax of ngRepeat.

As stated in the official documentation, the ngRepeat accepts an alias for the collection even if filter are applied to it:

<div ng-repeat="model in collection | filter:search | orderBy: 'id' as filtered_result track by model.id">
    {{model.name}}
</div>

Note: I added ad additional filter to the example copied from the documentation to have a more complete example.

In this example you can simply use:

<div class="alert alert-info" 
     ng-show="filtered_result.length == 0">
    No items in the collection!
</div>

I tested it with AngularJS 1.5.0, I can't tell when this feature was introduced.

like image 34
optimalab Avatar answered Nov 10 '22 01:11

optimalab