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

爱⌒轻易说出口 提交于 2019-12-25 02:44:12

问题


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.


回答1:


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>



回答2:


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.



来源:https://stackoverflow.com/questions/25263182/is-it-possible-to-limit-the-number-of-displayed-items-in-a-loop-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!