javascriptangularjsangularjs-directiveangularjs-ng-transclude

Add DOM element when transcluding except for the last one child


I would like to add a <hr> element between each clone of my transclude function except for the last one clone.

The parent directive have a custom HTML template.
In this template, I call a Attribute directive to transclude the elements.

Sample:

function directiveTransclude() {
    return {
        link: function (scope, element, attr, ctrl, transclude) {
            transclude(function (clone, scope) {
                element.append(clone);
            });
        }
    };
}

This directive help me to manually handle the transclude.
I just have to figure out now how to conditionnally add the <hr>.
I assume to do that I need to add for example element.append('<hr>'); after the first append.

So how could I know how many elements the transclude have to append ?
Is there a $last value or something to tell me that this is the last loop ?

Thanks for the help !


Solution

  • Just in case you wonder:

    It's late but I just find the solution by using an alternative (with CSS).

    As mentioned by @Aaron Pool, I can use last-child selector to achieve that.

    the last-of-type selector is finicky, and the last-child selector is actually applied to the child

    It's better (faster than DOM injection and safer visually speaking, because <hr> could easily get edited by CSS rules).

    I already tried that nevertheless it didn't works as expected.
    Despite, today I figure out that my LESS code was that:

    &:last-child
    

    Instead of

    :last-child
    

    So I was focusing the wrong DOM element, sadly.
    I'm happy even if now I feel so dumb.
    Greetings and happy new year !