如何在ng-repeat中使用ng-if实现每10个元素后换行?
Hey there! Let's break down why your current code isn't creating a new line every 10 elements, and how to fix it.
The Problem with Your Current Logic
Your line break condition <br ng-if="$index/10 == 0"> only triggers when $index is 0 (since 0 divided by 10 equals 0). For every other element, $index/10 will be a number greater than 0, so the break never shows up again after the first button. That's why you aren't seeing new lines every 10 items!
Quick Fix for Your Existing Code
You need to check if the current element is the 10th, 20th, 30th, etc. in the list. Since $index starts at 0, we can use the modulo operator to detect when we've hit a multiple of 10. The condition ($index + 1) % 10 === 0 will be true after every 10th element (because adding 1 shifts the index to match the human-readable count of buttons).
Here's your updated code:
<div class="row"> <div class="col-sm-1" ng-repeat="q in questions"> <button class="btn btn-danger" ng-click="select_question(q)">{{ $index + 1 }}</button> <br ng-if="($index + 1) % 10 === 0"> </div> <div class="col-sm-1"> <button class="btn btn-success" ng-click="select_new_question()">+</button> </div> </div>
A More Bootstrap-Friendly Alternative
If you want to align with Bootstrap's grid system more cleanly (instead of using <br>), you can group every 10 elements into a new .row container. This ensures your layout stays consistent with Bootstrap's responsive rules:
<!-- Group questions into rows of 10 --> <div ng-repeat="q in questions" ng-if="$index % 10 === 0"> <div class="row"> <!-- Loop through the 10 items in this group --> <div class="col-sm-1" ng-repeat="item in questions.slice($index, $index + 10)"> <button class="btn btn-danger" ng-click="select_question(item)">{{ $parent.$index + $index + 1 }}</button> </div> <!-- Add the "+" button to the final row --> <div class="col-sm-1" ng-if="$parent.$last"> <button class="btn btn-success" ng-click="select_new_question()">+</button> </div> </div> </div>
内容的提问来源于stack exchange,提问作者Shashishekhar Hasabnis

