Franva
Franva

Reputation: 7077

Is it possible to limit the number of displayed items in a loop in AngularJs

I have a list of categories and many questions which belongs to different categories.

{
    "id": 5,
    "description": "Does your site have Facebook?",
    "question_category_id": 3
  }

{
    "id": 1,
    "name": "Network",
    "description": "Network"
  }



<table ng-repeat="c in categories">
  <thead>
    <tr>
      <th>{{ c.id }}. {{ c.description }}</th>
    </tr>
  </thead>
  <tbody ng-repeat="q in questions | filter: { question_category_id: c.id } : true">
    <tr>
      <td>{{q.description}}</td>
    </tr>
  </tbody>
</table>

This is the code which displays all questions under a category.

But I want to loop through each of the categories and only display 1 question under one category by using AngularJs.

Is it possible ? If yes, how?

Thank you.

Upvotes: 0

Views: 70

Answers (2)

Mikko Viitala
Mikko Viitala

Reputation: 8404

If you really want to iterate over questions, then you could use $index.

<tbody 
    ng-repeat="q in questions | filter: { question_category_id: c.id } : true"
    ng-show="$index == 0">

If not, but still you do not want to touch the JavaScript part, then'd I'd go around this using

<td>
    {{ (questions | filter: { question_category_id: c.id } : true)[0].description }}
</td>

Upvotes: 0

pkit
pkit

Reputation: 81

You have a couple of possibilities here, check de documentation of ng-repeat (https://docs.angularjs.org/api/ng/directive/ngRepeat). For example if you only want to show the first question, you can check $first in ng-show on the tr-tag.

But be aware that this is only not showing the other questions of that category in the html, you still have retrieved all questions of that category from the server which is a waste of resources since you are only showing the first question.

Upvotes: 2

Related Questions