如何使用 ng 重复和固定行数创建水平网格

How to create a horizontal grid using ng-repeat and fixed number of rows

本文关键字:创建 水平 网格 ng 何使用      更新时间:2023-09-26

我有一个简单的文本对象数组,我想在网格中显示。这是使用Ionic框架。

网格必须是:

  1. 固定高度
  2. 正好 3 行
  3. 水平滚动(无限列)
  4. 2 个屏幕宽度<768 像素的可见列(手机),4 个可见列 768 像素及以上(平板电脑)

我有列宽的媒体查询,并用于水平滚动功能。

如何使用 ng-repeat(也许使用 ngif ??)来创建网格,从第一列开始并用 3 行填充该列,然后移动到下一列等)

.JS

var items = [
{text: "This is item1"},
{text: "This is item2"},
{text: "This is item3"},
.
.
.
]

.CSS:

.myGridRow {
  height: 40%;
 }
 .myGridCol {
   width: 50%;
 }
 @media only screen and (min-width : 768px) {
   .myGridCol {
     width: 25%;
   }
 }

.HTML

<ion-scroll direction="x">
 <div class="row myGridRow"> <!-- The single container for the whole grid -->
  <div ng-repeat="item in items"> <!-- only do this 3 times before starting a new row -->
   <div class="row"><div class="col myGridCol">{{item.text}}</div></div>
  </div>
</div>
</ion-scroll>

期望的输出

我被困在这里,试图确定如何在每 3 行之后移动到下一列,或者这是否是正确的方法。

ng-repeat被限制为迭代集合,并且无法使用整数作为输入。但是,您可以为所需的重复次数创建占位符集合:

$scope.items = [/* The base collection */];
$scope.iterCount = 3; // The number of iterations before a new row is created
$scope.itemCount = Math.floor($scope.items.length / $scope.iterCount);
// Get a collection of items equally spaced from each other. For
// example: getSpacedItems([1, 2, 3, 4], 0, 2) == [1, 3]
$scope.getSpacedItems = function(collection, start, space) {
  var subColl = [];
  for(var i = start; i < collection.length; i += space) {
    result.push(collection[i]);
  }
  return result;
};    

这些值可以通过以下方式应用于视图:

<div>
  <div class="row" ng-repeat="n in [0, 1, 2] track by $index">
    <div class="col myGridCol" ng-repeat="item in getSpacedItems(items, $index, iterCount)">{{item.text}}</div>
  </div>
</div>

我想这里的正确解决方案 - 在控制器端使用数据转换数组。所以你"旋转"你的2D数组,行变成列,列变成行。然后你只执行常规输出。这不是视图侧的任务。