I have a simple ng-repeat going on:
<div class="row-fluid">
<div class="span4" ng-repeat="piece in clothes | filter:query">
<img ng-src="{{piece.mainImage[0]}}" class="thumbImg" />
<a href="#/json/{{piece.systemName}}">{{piece.name}}</a>
</div>
</div>
After 3 repeats, I'd like to stop the repeat, add in a closing <div> and open a new .row-fluid (to start a new line), then re-start the loop where I left off, inserting the tags each 3rd time.
The docs for Angular are really hard to traverse, making it difficult to work out how to do this.
You could create a filter for array partitioning. (If you can use some library, you may be able to get something shorter & more efficient.)
app.filter('partition', function() {
var part = function(arr, size) {
if ( 0 === arr.length ) return [];
return [ arr.slice( 0, size ) ].concat( part( arr.slice( size ), size) );
};
return part;
});
You can use it like:
<div ng-repeat="rows in list | partition:3">
<div class="row" ng-repeat="item in rows">
<div class="span4">{{ item }}</div>
</div>
</div>
ngRepeat will keep re-evaluating the filter infinitely because it gets different values every time it's ran.
This terrible code seems to work in the general case. If you have identical arrays things could get hairy. We need to be able to compare arrays for equality, but that's a difficult problem. I took the easy/flimsy way out and just used stringify(). Could not get angular.equals() to work for me; I think it probably just works on shallow objects.
app.filter('partition', function($cacheFactory) {
var arrayCache = $cacheFactory('partition')
return function(arr, size) {
var parts = [], cachedParts,
jsonArr = JSON.stringify(arr);
for (var i=0; i < arr.length; i += size) {
parts.push(arr.slice(i, i + size));
}
cachedParts = arrayCache.get(jsonArr);
if (JSON.stringify(cachedParts) === JSON.stringify(parts)) {
return cachedParts;
}
arrayCache.put(jsonArr, parts);
return parts;
};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With