当转发器中的对象为空时,AngularJS显示消息

时间:2013-04-14 01:09:09

标签: javascript angularjs

我正在使用AngularJS和转发器来迭代一些结果。还有一个应用于搜索的过滤器。

我希望能够处理两种情况,并且正在寻找最“有棱角”的方式。

第一个条件是如果没有开始的结果。

第二个条件是,如果使用过滤器,则不会返回任何结果。

我看到了this,这似乎已经足够了,我可以为每个条件创建一个。但是,无论如何都有原生角度指令来处理这些条件,而不需要控制器中的代码吗?

谢谢!

3 个答案:

答案 0 :(得分:12)

您可以在已过滤的数组上添加ngSwitch指令,并根据其长度显示不同的HTML。

jsFiddle

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:

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'
}];
}

另一种选择是直接在控制器中对friends数组应用$ filter(“filter”),这将缩短HTML标记。

答案 1 :(得分:6)

您可以使用此语法在找不到数据时显示消息

<p ng-show="(friends | filter:searchText).length==0">Sorry No Result Found</p>` 

朋友是JSON对象。

答案 2 :(得分:1)

ngRepeat允许您在处理完所有过滤器后为结果项目提供别名。 然后,您可以使用此别名来显示您的消息。

<p ng-repeat="friend in friends | filter:searchText as displayedFriends">
    {{friend.name}}
</p>
<p ng-if="!displayedFriends.length">
    Nothing was found
</p>
相关问题