javascript 当中继器中的对象为空时,AngularJS 显示消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15994666/
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
AngularJS display message when object is empty in repeater
提问by dzm
I'm using AngularJS and the repeater to iterate through some results. There's also a filter applied for searching.
我正在使用 AngularJS 和转发器来迭代一些结果。还有一个过滤器用于搜索。
There's two conditions that I would want to be able to handle and am looking for the most "angular" way.
我希望能够处理两种情况,并且正在寻找最“有角度”的方式。
The first condition is if there are no results to begin with.
第一个条件是如果开始时没有结果。
The second condition is if when using the filter, there are no results returned.
第二个条件是,如果使用过滤器时,没有返回任何结果。
I saw this, which seems like it would be adequate and I could create one for each condition. However, is there anyway with native angular directives to handle these conditions, without requiring code in the controller?
我看到了这个,这似乎就足够了,我可以为每个条件创建一个。但是,无论如何,是否有本地角度指令来处理这些条件,而无需控制器中的代码?
Thanks!
谢谢!
回答by Klaster_1
You can add ngSwitch directive on filtered array and display different HTML depending on it's length.
您可以在过滤后的数组上添加 ngSwitch 指令并根据其长度显示不同的 HTML。
HTML:
HTML:
<div ng-app ng-controller="Ctrl">
Search: <input ng-model="searchText">
<div ng-init="filtered = (friends | filter:searchText)">
<div>{{(friends | filter:searchText).length}}</div>
<div ng-switch="(friends | filter:searchText).length">
<span ng-switch-when="0">Nothing was found</span>
<table id="searchTextResults" ng-switch-default>
<tr>
<th>Name</th>
<th>Phone</th>
</tr>
<tr ng-repeat="friend in filtered | filter:searchText">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
</tr>
</table>
</div>
</div>
JS:
JS:
function Ctrl($scope) {
$scope.searchText = "";
$scope.friends = [{
name: 'John',
phone: '555-1276'
}, {
name: 'Mary',
phone: '800-BIG-MARY'
}, {
name: 'Mike',
phone: '555-4321'
}, {
name: 'Adam',
phone: '555-5678'
}, {
name: 'Julie',
phone: '555-8765'
}];
}
Another option is to apply $filter("filter") on friends array directly in controller, which will shorten HTML markup.
另一种选择是直接在控制器中对朋友数组应用 $filter("filter") ,这将缩短 HTML 标记。
回答by Rajnish Bakaria
You Can Use This Syntax For Showing Message When No Data Found
您可以使用此语法在未找到数据时显示消息
<p ng-show="(friends | filter:searchText).length==0">Sorry No Result Found</p>`
Where friends is the JSON object.
其中friends 是JSON 对象。
回答by Julien
ngRepeatallows you to give an alias to the resulting items after all filters have been processed. You can then use this alias to display your message.
ngRepeat允许您在处理完所有过滤器后为结果项指定别名。然后您可以使用此别名来显示您的消息。
<p ng-repeat="friend in friends | filter:searchText as displayedFriends">
{{friend.name}}
</p>
<p ng-if="!displayedFriends.length">
Nothing was found
</p>