AngularJS ng-repeat handle empty list case

后端 未结 10 2067
隐瞒了意图╮
隐瞒了意图╮ 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 16:59
    <ul>
        <li ng-repeat="item in items | filter:keyword as filteredItems">
            ...
        </li>
        <li ng-if="filteredItems.length===0">
            No items found
        </li>
    </ul>
    

    This is similar to @Konrad 'ktoso' Malawski but slightly easier to remember.

    Tested with Angular 1.4

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

    You might want to check out the angular-ui directive ui-if if you just want to remove the ul from the DOM when the list is empty:

    <ul ui-if="!!events.length">
        <li ng-repeat="event in events">{{event.title}}</li>
    </ul>
    
    0 讨论(0)
  • 2020-11-30 17:11

    You can use ngShow.

    <li ng-show="!events.length">No events</li>
    

    See example.

    Or you can use ngHide

    <li ng-hide="events.length">No events</li>
    

    See example.

    For object you can test Object.keys.

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

    With the newer versions of angularjs the correct answer to this question is to use ng-if:

    <ul>
      <li ng-if="list.length === 0">( No items in this list yet! )</li>
      <li ng-repeat="item in list">{{ item }}</li>
    </ul>
    

    This solution will not flicker when the list is about to download either because the list has to be defined and with a length of 0 for the message to display.

    Here is a plunker to show it in use: http://plnkr.co/edit/in7ha1wTlpuVgamiOblS?p=preview

    Tip: You can also show a loading text or spinner:

      <li ng-if="!list">( Loading... )</li>
    
    0 讨论(0)
  • 2020-11-30 17:15

    you can use ng-if because this is not render in html page and you dont see your html tag in inspect...

    <ul ng-repeat="item in items" ng-if="items.length > 0">
        <li>{{item}}<li>
    </ul>
    <div class="alert alert-info">there is no items!</div>
    
    0 讨论(0)
  • 2020-11-30 17:16

    i usually use ng-show

    <li ng-show="variable.length"></li>
    

    where variable you define for example

    <div class="list-group-item" ng-repeat="product in store.products">
       <li ng-show="product.length">show something</li>
    </div>
    
    0 讨论(0)
提交回复
热议问题