Home  >  Article  >  Web Front-end  >  How to Split ng-repeat Data into Three Columns Using Bootstrap?

How to Split ng-repeat Data into Three Columns Using Bootstrap?

Linda Hamilton
Linda HamiltonOriginal
2024-10-25 01:01:30638browse

How to Split ng-repeat Data into Three Columns Using Bootstrap?

Splitting ng-repeat Data into Three Columns Using Bootstrap

When working with ng-repeat in AngularJS, it's common to want to arrange data into multiple columns. This article explores different methods for splitting ng-repeat data into three columns using Bootstrap.

Data Transformation in Controller

The most reliable approach is to transform the data in the controller. This allows you to maintain the original data structure while creating a new array of chunked data. You can use a function like the following:

<code class="javascript">function chunk(arr, size) {
  var newArr = [];
  for (var i=0; i<arr.length; i+=size) {
    newArr.push(arr.slice(i, i+size));
  }
  return newArr;
}

$scope.chunkedData = chunk(myData, 3);

In your view, iterate over the chunked data:

<code class="html"><div class="row" ng-repeat="rows in chunkedData">
  <div class="span4" ng-repeat="item in rows">{{item}}</div>
</div></code>

Filter in the View (Not Recommended for Inputs)

While it's possible to use a filter to display chunked data, it's important to note that this method is not suitable for use with inputs. Instead, rely on data transformation in the controller.

Vertical Columns

For vertical column layouts, you can modify the CSS or use custom functions to arrange the elements:

CSS Columns (Preferred)

<code class="css">.columns {
  columns: 3;
}</code>
<code class="html"><div class="columns">
  <div ng-repeat="item in ['a','b','c','d','e','f','g']">{{item}}</div>
</div></code>

Custom Function

Alternatively, you can distribute uneven lists vertically using a custom function:

<code class="javascript">var data = ['a','b','c','d','e','f','g'];
$scope.columns = columnize(data, 3);
function columnize(input, cols) {
  var arr = [];
  for(i = 0; i < input.length; i++) {
    var colIdx = i % cols;
    arr[colIdx] = arr[colIdx] || [];
    arr[colIdx].push(input[i]);
  }
  return arr;
}</code>

The above is the detailed content of How to Split ng-repeat Data into Three Columns Using Bootstrap?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn