Home  >  Article  >  Web Front-end  >  How can I align AngularJS ng-repeat data into three Bootstrap columns?

How can I align AngularJS ng-repeat data into three Bootstrap columns?

DDD
DDDOriginal
2024-10-25 01:37:30130browse

How can I align AngularJS ng-repeat data into three Bootstrap columns?

Aligning AngularJS ng-repeat Data in Three Bootstrap Columns

AngularJS provides ng-repeat to dynamically create elements based on an array of data. When you're dealing with a significant number of elements, aligning them into columns can enhance the user interface and readability.

Controller-Based Transformation

The preferred approach is to transform the data within the controller using JavaScript's chunk function, which breaks the data into evenly sized groups:

<code class="js">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);

The transformed chunkedData can then be rendered in the view as follows:

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

Filtering in the View (Caution)

Although possible, using filters to chunk the data in the view is not recommended for data binding purposes. If inputs are used within the filtered view, it can lead to inconsistencies.

<code class="html"><pre class="brush:php;toolbar:false">
<div ng-repeat="row in ['a','b','c','d','e','f'] | chunk:3">
  <div class="column" ng-repeat="item in row">
    {{($parent.$index*row.length)+$index+1}}. {{item}}
  </div>
</div>

Vertical Columns

To align items vertically instead of horizontally, a variation of the chunking method can be used:

<code class="js">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 class="html"><div ng-repeat="row in columns">
  <div class="column" ng-repeat="item in row">
    {{item}}
  </div>
</div></code>

CSS Columns

Another option for creating vertical columns is to leverage CSS columns:

<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>

The above is the detailed content of How can I align AngularJS ng-repeat data into three Bootstrap columns?. 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