Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS display message when object is empty in repeater

I'm using AngularJS and the repeater to iterate through some results. There's also a filter applied for searching.

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!

like image 932
dzm Avatar asked Apr 14 '13 01:04

dzm


3 Answers

You can add ngSwitch directive on filtered array and display different HTML depending on it's length.

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

Another option is to apply $filter("filter") on friends array directly in controller, which will shorten HTML markup.

like image 65
Klaster_1 Avatar answered Nov 15 '22 20:11

Klaster_1


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.

like image 25
Rajnish Bakaria Avatar answered Nov 15 '22 21:11

Rajnish Bakaria


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

<p ng-repeat="friend in friends | filter:searchText as displayedFriends">
    {{friend.name}}
</p>
<p ng-if="!displayedFriends.length">
    Nothing was found
</p>
like image 1
Julien Avatar answered Nov 15 '22 20:11

Julien