Horizontal ng-repeat(er) with new row breaks
If you are working with Bootstrap 3 and AngularJS you can declare a new filter that will return one array of sub array slices and then do two ng-repeat.
It will look like that:
<div class="row" ng-repeat="row in filtered = (arr | splitArrayFilter:3)"> <div class="col-md-4" ng-repeat="n in row"> <h3>{{n}}</h3> </div> </div>
app.filter('splitArrayFilter', function() { return function(arr, lengthofsublist) { if (!angular.isUndefined(arr) && arr.length > 0) { var arrayToReturn = []; var subArray=[]; var pushed=true; for (var i=0; i<arr.length; i++){ if ((i+1)%lengthofsublist==0) { subArray.push(arr[i]); arrayToReturn.push(subArray); subArray=[]; pushed=true; } else { subArray.push(arr[i]); pushed=false; } } if (!pushed) arrayToReturn.push(subArray); console.log(JSON.stringify(arrayToReturn)); return arrayToReturn; } }});
You can Find it on Plunker here: http://plnkr.co/edit/rdyjRtZhzHjWiWDJ8FKJ?p=previewfor some reason the view in plunker does not support bootstrap 3 columns but if you open it in embedded view or in browsers you can see that it works.
It was clever what you were doing with ng-class
. I hadn't ever thought of using %2
within the expression there.
But for future reference, there is a slightly easier way to accomplish that: ng-class-even
and ng-class-odd
. It does the same thing as what you were doing, but just a bit cleaner:
<div ng-repeat="num in numbers" ng-class-even="'md-col-6'" ng-class-odd="'row'"> {{num}}</div>
But this doesn't resolve your problem. If I understand you correctly, you want a row, with two columns within that row. The easiest way I could think of is to split up the arrays. Put the repeat on the div
, then have 2 span
within the div
. I think one of the issues that you had originally, is that you were repeating a single div
, and trying to treat that block
element as an inline
Controller
myApp.controller('MyCtrl', function ($scope) { $scope.evens = ["2","4","6","8","10","12","14"]; $scope.odds = ["1","3","5","7","9","11","13"];});
HTML
<div ng-controller="MyCtrl"> <div ng-repeat="odd in odds" class="row"> <span class="span3">{{odd}}</span> <span class="span2">{{evens[$index]}}</span> </div></div>
Being that you're using version 1.1.5, that also opens you up to a new directive: ng-if
! You could also use ng-switch
to do some conditional logic displays.
You didn't include bootstrap in your fiddle, and for some reason I can't get jsFiddle to display bootstrap. So I created some temp CSS classes that would somewhat resemble bootstraps class="span"
No need to add .row class .. I did this:
HTML:
<div ng-repeat="product in allProducts"> <div class="my-col-50"> <h1>{{product.title}}</h1> </div></div>
CSS:
.my-col-50{float:left;width:50%;}
and it's work like a charm.