javascript 如何在过滤器在 ng-repeat 中不返回任何内容时显示消息 - AngularJS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21524572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:06:12  来源:igfitidea点击:

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

javascriptangularjsangularjs-ng-repeat

提问by shaik

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

当过滤器(ng-repeat)上没有返回任何项目时,我想显示一个div(消息)。

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?

过滤器是基于选择框(ng-model)发生的。并且某些选择选项没有结果,此时用户应该能够在同一位置阅读消息。我可以在这里使用 ng-show/hide 吗?如何?

Thanks,

谢谢,

回答by muenchdo

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

您还可以将过滤后的数组保存在一个变量中,然后在ng-show表达式中使用该变量:

<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.

您可以在这个plunker 中看到它的运行情况

回答by Chandermani

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

您可以使用类似的方法获取过滤器返回的数组大小

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

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

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

您可以使用此表达式进行ng-show表达式。我不确定它的性能如何。

回答by optimalab

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

仅使用 ngRepeat 的标准语法有一个更简单的解决方案。

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

正如官方文档中所述,即使应用了过滤器,ngRepeat 也接受集合的别名:

<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.

我用 AngularJS 1.5.0 测试过,我不知道这个功能是什么时候引入的。