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

青春壹個敷衍的年華 提交于 2019-11-27 13:42:49

问题


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,


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/21524572/how-to-show-a-message-when-filter-returns-nothing-in-ng-repeat-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!