Home >Web Front-end >JS Tutorial >How to distribute ng-repeat data into columns using Bootstrap in AngularJS?
In AngularJS, leveraging ng-repeat is fundamental when working with repetitive data. However, the need often arises to organize these elements into a visually appealing layout, such as three distinct columns. To achieve this, we delve into various approaches, including both controller-level and view-level solutions.
Controller-Level Transformation
A robust approach lies in transforming the data within the controller. By leveraging the provided chunk function, we can divide the data into equal subarrays, each representing one column:
<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);
This data can then be rendered using a nested ng-repeat, 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>
View-Level Filtering
Alternatively, a filter can be used to achieve the desired layout within the view. However, this approach is primarily intended for display purposes and may encounter issues when incorporating input elements:
<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 Columnization
To distribute items vertically rather than horizontally, slight alterations to the aforementioned approaches can be made:
<code class="html"><div ng-repeat="row in columns"> <div class="column" ng-repeat="item in row"> {{item}} </div> </div></code>
<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; }
CSS Columns
Another elegant solution involves leveraging CSS columns:
<code class="css">.columns { columns: 3; }
<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 to distribute ng-repeat data into columns using Bootstrap in AngularJS?. For more information, please follow other related articles on the PHP Chinese website!