"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How can I align AngularJS ng-repeat data into three Bootstrap columns?

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

Published on 2024-11-08
Browse:589

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:

function chunk(arr, size) {
  var newArr = [];
  for (var i=0; i

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

{{item}}

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.

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

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

CSS Columns

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

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

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3