1

I have nested ng-repeat Something like this. I want to limit it to only use the first 2 items in the list (not the full list).

ng-repeat = "items in phone.comments 

and the HTML:

      <div class="wallList clearfix" ng-repeat = "items in phone.comments | limitTo:quantity">
        <div class="wallListImage">
          <a href="#">
            <img ng-show = "items.imageUrl" ng-src="{{items.imageUrl}}" height = "42px" width= "42px"/>
            <img ng-show = "!items.imageUrl" ng-src="WishlistImage/movies.png" height = "42px" width= "42px"/>
          </a>
        </div>
      </div>
2
  • 1
    What is the question? What doesn't work? …
    – Blackhole
    May 29, 2014 at 14:28
  • I believe he's asking how to limit the ng-repeat to only the first 2 items, rather than repeating over the whole list.
    – spikeheap
    May 29, 2014 at 14:36

2 Answers 2

6

I looks like you're on the right track. Assuming you've defined a $scope.quantity, your code should work. Like you have in your example, I would recommend using the 'limitTo' filter.

Example of it's use:

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

You can see a live example here:

http://jsfiddle.net/Nu7rZ/

A similar Stack Overflow question was asked here:

Way to ng-repeat defined number of times instead of repeating over array?

4
  • 1
    Great answer, and a lot more "Angular" than using '.slice'.
    – spikeheap
    May 29, 2014 at 15:09
  • I want to toggle comments in 2 and view all . for each section May 30, 2014 at 6:31
  • Is this a streaming solution or does it load all of the data being called and then slice it?
    – i i
    Sep 21, 2016 at 21:14
  • 1
    Hey @Barry - It should be! Angular's ng-repeat gets updated on the app's digest cycle. So any changes to the data should get reflected, and run through the relevant filters. It's one of the great benefits of Angular's data binding. For more information than you could ever ask for, here's a great article on angular magic, ng-repeat and the DOM: bennadel.com/blog/… Sep 22, 2016 at 18:15
2

You can limit it explicitly in your ng-repeat statement by using:

ng-repeat="items in phone.comments.slice(0,2)"

The JavaScript slice function takes the start (inclusive) and end (exclusive) array indices, so the above will give you the first two items.

See http://jsfiddle.net/spikeheap/9fBvT/ for a working example. Also see http://www.w3schools.com/jsref/jsref_slice_array.asp for more information about slice.

You may want to consider moving the slice into the controller, but that depends on your use case and personal preference.

Not the answer you're looking for? Browse other questions tagged or ask your own question.