Monday, January 27, 2014

Breaking up ng-repeat into rows

Recently I had to get an array of an undetermined number of items to fit into a bunch of rows (bootstrap) using angular and the ng-repeat directive. What I did..

In Html:
--
<div class="row" ng-repeat="r in getDataRowsArray()"> <div class="col-md-2" ng-repeat="c in getDataInRow(r)"> <span>{{c.SomeField}}</span> </div> </div>
--
In the controller, the methods were as follows (with a scope.DataPerRow defined = 6). The code is meant to be readable; I know that with underscore or something similar this can be more expressive.
--
$scope.getDataRowsArray = function(){
                var n = Math.ceil(scope.Data.length / $scope.DataPerRow);
                var ret = [];
                for (var i = 0; i < n;i++){
                    ret.push(i);
                }
                return ret;
            }
--
$scope.getDataInRow = function(rowNum){
                var ret = [];
                for (var i = rowNum * $scope.DataPerRow; i < $scope.Data.length && i < $scope.DataPerRow * (rowNum + 1);i++){
                    ret.push($scope.Data[i]);
                }
                return ret;
            }
--