Home >Web Front-end >JS Tutorial >How can I align AngularJS ng-repeat data into 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.
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>
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>
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>
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!