【问题标题】:How to create a horizontal grid using ng-repeat and fixed number of rows如何使用 ng-repeat 和固定行数创建水平网格
【发布时间】:2016-02-06 20:12:06
【问题描述】:

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

网格必须是:

  1. 固定高度
  2. 正好 3 行
  3. 水平卷轴(无限列)
  4. 2 个屏幕宽度

我有列宽的媒体查询,并且正在使用水平滚动功能。

我如何使用 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>

Desired Output

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

【问题讨论】:

  • 你能分享一下你想要的输出应该是什么样子吗?
  • @gnerkus 我刚刚在问题中添加了所需的输出。感谢收看。
  • 有点难读。你能格式化一下吗?您可以使用硬编码的 HTML 来显示所需的输出。
  • 多年来,我已经与许多人详细讨论过这个问题。如果你使用响应式框架来处理你的 CSS,你不应该期望 Angular 来操纵你的数据来尝试创建你想要的屏幕布局。这确实是 CSS 的工作;任何时候你试图“欺骗”角度框架来生成新行而不是让 CSS 来完成这项工作,你不仅会增加复杂性,而且还会冒着破坏与数据的双向绑定的风险。

标签: javascript angularjs ionic-framework


【解决方案1】:

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>

【讨论】:

  • 此方案先填写第一行,再填写第二行,依此类推......不是按要求填写第一列,第二列等。我需要这个,因为这是一个水平滚动容器。
  • 我已对解决方案进行了更正。我有点误解了这个问题。谢谢你的澄清。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2013-12-06
    • 1970-01-01
    • 1970-01-01
    • 2017-09-29
    • 2018-01-07
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    • 2014-09-14
    相关资源
    最近更新 更多