AngularJS ng-repeat handle empty list case

后端 未结 10 2122
隐瞒了意图╮
隐瞒了意图╮ 2020-11-30 16:47

I thought this would be a very common thing, but I couldn\'t find how to handle it in AngularJS. Let\'s say I have a list of events and want to output them with AngularJS, t

相关标签:
10条回答
  • 2020-11-30 17:17

    And if you want to use this with a filtered list here's a neat trick:

    <ul>
        <li ng-repeat="item in filteredItems  = (items | filter:keyword)">
            ...
        </li>
    </ul>
    <div ng-hide="filteredItems.length">No items found</div>
    
    0 讨论(0)
  • 2020-11-30 17:19

    You can use this ng-switch:

    <div ng-app ng-controller="friendsCtrl">
      <label>Search: </label><input ng-model="searchText" type="text">
      <div ng-init="filtered = (friends | filter:searchText)">
      <h3>'Found '{{(friends | filter:searchText).length}} friends</h3>
      <div ng-switch="(friends | filter:searchText).length">
        <span class="ng-empty" ng-switch-when="0">No friends</span>
        <table ng-switch-default>
          <thead>  
            <tr>
              <th>Name</th>
              <th>Phone</th>
            </tr>
          </thead>
          <tbody>
          <tr ng-repeat="friend in friends | filter:searchText">
            <td>{{friend.name}}</td>
            <td>{{friend.phone}}</td>
          </tr>
        </tbody>
      </table>
    </div>
    
    0 讨论(0)
  • 2020-11-30 17:23

    Here's a different approach using CSS instead of JavaScript/AngularJS.

    CSS:

    .emptymsg {
      display: list-item;
    }
    
    li + .emptymsg {
      display: none;
    }
    

    Markup:

    <ul>
        <li ng-repeat="item in filteredItems"> ... </li>
        <li class="emptymsg">No items found</li>
    </ul>
    

    If the list is empty, <li ng-repeat="item in filteredItems">, etc. will get commented out and will become a comment instead of a li element.

    0 讨论(0)
  • 2020-11-30 17:24

    You can use as keyword to refer a collection under a ng-repeat element:

    <table>
        <tr ng-repeat="task in tasks | filter:category | filter:query as res">
            <td>{{task.id}}</td>
            <td>{{task.description}}</td>
        </tr>
        <tr ng-if="res.length === 0">
            <td colspan="2">no results</td>
        </tr>
    </table>
    
    0 讨论(0)
提交回复
热议问题