我正在尝试使用 bootstrap 3 和 angularjs 创建网格。
我正在尝试创建的网格是这样的,使用 ng-repeat 重复。
<div class="row">
<div class="col-md-4">item</div>
<div class="col-md-4">item</div>
<div class="col-md-4">item</div>
</div>
我已经尝试使用 ng-if
和 ($index % 3 == 0)
来添加行,但这似乎无法正常工作.任何建议都会很棒!
谢谢!
编辑:这是我最终使用的有效代码:
<div ng-repeat="item in items">
<div ng-class="row|($index % 3 == 0)">
<ng-include class="col-sm-4" src="'views/items/item'"></ng-include>
</div>
</div>
最佳答案
公认的答案是显而易见的解决方案,但是表示逻辑应该保留在 View 中,而不是在 Controller 或模型中。此外,我无法让 OP 的解决方案发挥作用。
当你有一个扁平的项目列表(数组)时,这里有两种创建网格系统的方法。 假设我们的项目列表是一个字母表:
$scope.alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
方法一:
这是一个纯 Angular 解决方案。
<div class="row" ng-repeat="letter in alphabet track by $index" ng-if="$index % 4 == 0">
<div class="col-xs-3 letter-box"
ng-repeat="i in [$index, $index + 1, $index + 2, $index + 3]"
ng-if="alphabet[i] != null">
<div>Letter {{i + 1}} is: <b> {{alphabet[i]}}</b></div>
</div>
</div>
外循环在每 4 次迭代后执行并创建一行。对于外循环的每次运行,内循环迭代 4 次并创建列。由于无论数组中是否有元素,内部循环都会运行 4 次,ng-if
确保如果数组在内部循环完成之前结束,则不会创建无关的列。
方法二:
这是更简单的解决方案,但需要 angular-filter图书馆。
<div class="row" ng-repeat="letters in alphabet | chunkBy:4">
<div class="col-xs-3 letter-box" ng-repeat="letter in letters" >
<div>Letter {{$index + 1}} is: <b> {{letter}}</b></div>
</div>
</div>
外层循环创建了一组 4 个字母,对应于我们的“行”
[['A', 'B', 'C', 'D'], ['E', 'F', 'G', 'H'], ... ]
内部循环遍历组并创建列。
注意:方法 2 可能需要为外循环的每次迭代评估过滤器,因此方法 2 可能无法很好地扩展到庞大的数据集。
关于javascript - angular.js ng-repeat 用于创建网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20137496/