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.
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; iThe 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>
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>
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>
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