I have an array of items. And I need to wrap a bunch of these items after a predefined amount. eg.:
<div>
<span>1</span>
<span>2</span>
<span>3</span>
</div>
<div>
<span>4</span>
</div>
This is because of Bootstrap Grid usage.
Now I am using AngularJS and have such a construct:
<span ng-repeat="item in items"></span>
And after a certain amount I need to wrap it. I tried to make a directive for that, but I'm pretty sure it got much room for improvement:
app.directive('wrapper', function(){
var itemsToWrap = [];
return {
restrict: 'A',
link: function(scope, element, attributes) {
scope.$watch(attributes.wrapper, function(newVal){
itemsToWrap.push(element);
if (newVal) {
for (var i = 0; i < itemsToWrap.length; i++) {
angular.element(itemsToWrap[i]).addClass('gnarf');
}
angular.element('.gnarf').wrapAll('<div />');
for (var i = 0; i < itemsToWrap.length; i++) {
angular.element(itemsToWrap[i]).removeClass('gnarf');
}
itemsToWrap = [];
}
});
}
}
});
The call in html is:
<span ng-repeat="item in items" wrapper="$index % 3 == 2">
{{item}}
</span>
It works, but I think the solution with using a css class to use jQuery's wrapAll() is not the best idea. But I had the problem to convert the array itemsToWrap
to an array which works with jQuery wrapAll();
Furthermore: How would you keep the wrapping tag flexible? Simple as attribute?
Thanks in advance!