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!