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>
spikeheap
  • 3,827
  • 1
  • 32
  • 47
Ashisha Nautiyal
  • 1,389
  • 2
  • 19
  • 39

2 Answers2

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?

Community
  • 1
  • 1
Alex Johnson
  • 1,504
  • 13
  • 20
  • 1
    Great answer, and a lot more "Angular" than using '.slice'. – spikeheap May 29 '14 at 15:09
  • I want to toggle comments in 2 and view all . for each section – Ashisha Nautiyal May 30 '14 at 06:31
  • Is this a streaming solution or does it load all of the data being called and then slice it? – Barry Sep 21 '16 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: http://www.bennadel.com/blog/2443-rendering-dom-elements-with-ngrepeat-in-angularjs.htm – Alex Johnson Sep 22 '16 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.

spikeheap
  • 3,827
  • 1
  • 32
  • 47