0

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!

Armin
  • 15,582
  • 10
  • 47
  • 64
  • possible duplicate of [Wrap every 3 divs in a div](http://stackoverflow.com/questions/3366529/wrap-every-3-divs-in-a-div) – Jay Blanchard Jun 20 '14 at 17:22
  • No, these answers don't help me, because I am here in AngularJS context and the elements I got are stored in a normal array, without jQuery magic. My problem basically is, how to convert a normal array to a jQuery wrapped one, and how to improve this AngularJS directive. – Armin Jun 21 '14 at 10:06

1 Answers1

0

I've got another approach:

app.directive('wrapper', function(){
    var itemsToWrap = angular.element();
    return {
        restrict: 'A',
        link: function(scope, element, attributes) {
            scope.$watch(attributes.wrapper, function(newVal){
                jQuery.merge(itemsToWrap, element);
                if (newVal) {
                    itemsToWrap.wrapAll('<div />');
                    itemsToWrap = angular.element();
                }
            });
        }
    }
});

This works, but it requires jQuery. But I think jQuery is required nevertheless, because of the wrapAll() function. This approach is at least a bit nicer than the one in the question.

Armin
  • 15,582
  • 10
  • 47
  • 64