如何在使用ng-repeat时将数据分成一半?

时间:2015-03-06 13:13:58

标签: javascript angularjs filter ng-repeat

我有一些数据,我可以使用div将此数据汇编到ng-repeat。我试图将它们分成2列,并且找不到构建它的方法。

以下是我的示例: ( jsFiddle )

HTML:

<div ng-controller="Ctrl">
    <div class="left">
      <div ng-repeat="item in data">{{item.value}}</div>
      <!-- i've tried filter and failed -->
    </div>
    <div class="right">
      <div ng-repeat="item in data">{{item.value}}</div>
    </div>
</div>

JS:

var app = angular.module('app', []);
function Ctrl($scope) {
  $scope.data = [
      {value: "a"},
      {value: "b"},
      {value: "c"},
      {value: "d"},// trying to divide from here
      {value: "e"},// and show the last part in other column
      {value: "f"},
      {value: "g"},
      {value: "h"}
  ];
}

4 个答案:

答案 0 :(得分:14)

甚至还有一个更简洁的解决方案,但您必须使用角度1.2.1:https://jsfiddle.net/1fch1221/6/

<div ng-controller="Ctrl">
<div class="left">
  <div ng-repeat="item in data" ng-if="$index < (data.length / 2)">{{item.value}}</div>

      <!-- i've tried filter and failed -->
</div>
<div class="right">
  <div ng-repeat="item in data" ng-if="$index >= (data.length / 2)">{{item.value}}</div>
</div>

答案 1 :(得分:7)

您可以使用两个变量,例如

function Ctrl($scope) {
  $scope.data = [
      {value: "a"},
      {value: "b"},
      {value: "c"},
      {value: "d"},// trying to divide from here
      {value: "e"},// and show the last part in other column
      {value: "f"},
      {value: "g"},
      {value: "h"}
  ];

  var len = $scope.data.length,
      mid = len / 2;

  $scope.left  = $scope.data.slice(0, mid);  
  $scope.right = $scope.data.slice(mid, len);
}

Example

答案 2 :(得分:2)

我不知道它比其他答案更干净,但是作为想法:

ng-repeat="item in data.slice(0, data.length / 2)"
ng-repeat="item in data.slice(data.length / 2, data.length)"

答案 3 :(得分:1)

我认为这里最简单的解决方案是将数据数组划分为2个不同的变量。如果你不能这样做,你也可以编写一个测试函数来决定是否显示给定的值。

<div ng-repeat="item in data" ng-show="test(item.value)"

我的建议JSFiddle:here