Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ng-repeat and limitTo to limit the number of visible items displayed

I'm trying to limit my result sets to a fixed number. I can use limitTo with ng-repeat, but this limits items regardless of their current visibility and removes items from the DOM. I want to limit to a number of visible items while keeping everything in the DOM.

Here is the current code that I have. My goal is to always show no more than 50 items in the list even though items contains 500 items.

<div ng-repeat="item in items | limitTo: 50">
  <div ng-show="item.visible">
    <p>item.id</p>
  </div>
</div>

This will initially limit to 50 items, but if I filter the list (by modifying item.visible on some items), the list never shows items in the range of 50 - 500 and instead displays less than 50 items. What's the right way to limit an ng-repeat so that it only counts visible items towards the limit restriction?

like image 415
Bill Avatar asked Oct 25 '13 23:10

Bill


4 Answers

You can use:

<div ng-repeat="item in items | filter:{visible: true} | limitTo: 50">
    <p>{{item.id}}</p>
</div>

filter:{visible: true} will return a list of all visible items

You can take a look at the angularjs docu for more information on the filter filter. http://docs.angularjs.org/api/ng.filter:filter

like image 90
bekite Avatar answered Nov 15 '22 12:11

bekite


It is also possible to do it this way:

<div ng-repeat="item in items" ng-show="$index<50">
    <p>item.id</p>
</div>
like image 27
Kostyantyn Avatar answered Nov 15 '22 11:11

Kostyantyn


There are a couple of approaches, maybe the most reusable is for you to create your own 'visible' custom filter which looks for visible attribute on your items. Then you could chain them.

<div ng-repeat="item in items | visible | limitTo: 50">

Here's a SO link to create custom filters

like image 1
Dan Doyon Avatar answered Nov 15 '22 12:11

Dan Doyon


You can use ng-if with $index to specify DOM display. Still generates ng-if comments but doesn't load the object so much improved performance noticed.

<div ng-init="your.objects={{},{},{}}; your.max=10">
  <div ng-repeat="object in your.objects" ng-if="$index<your.max">
    {{object}}
  </div>
</div>
like image 1
irth Avatar answered Nov 15 '22 11:11

irth