Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs ng-repeat and child elements

I'm attempting to insert a <br/> every nth element to achieve something like this (using ng-repeat and ng-if="!($index % 2)"):

<div class="container">
    <div>
        <span>1</span>
        <span>2</span>
        <br/>
        <span>3</span>
    </div>
</div>

I thought I could mimic how i've used ng-repeat in the past for <ul/> elements, as so:

<div class="container">
    <ul ng-repeat="item in list">
        <li>{{item}}</li>
    </ul>
</div>

which produces a list such as this:

<div class="container">
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
</div>

Yet when I attempt to do something like this:

<div class="container">
    <div ng-repeat="item in list">
        <span>{{item}}</span>
    </div>
</div>

I get this differing result from the <ul/> usecase:

<div class="container">
    <div>
        <span>1</span>
    </div>
    <div>
        <span>2</span>
    </div>
    <div>
        <span>3</span>
    </div>
</div>

The question is two-fold:

  • Why does the ng-repeat directive on a <ul/> behave differently
  • How can I have multiple span elements then a break without wrapping each span in a div?
like image 565
Vetsin Avatar asked May 13 '26 20:05

Vetsin


1 Answers

https://docs.angularjs.org/api/ng/directive/ngRepeat

The ngRepeat directive instantiates a template once per item from a collection. Each template instance gets its own scope, where the given loop variable is set to the current collection item, and $index is set to the item index or key.

In your loop, your 'item' has following local variables: $index, $first, $middle, $last, $even, $odd. Each except $index returns a boolean value that tells you if the item is, for example, $odd. Also take a look at the directive ngClassEven.

like image 194
TurtleTread Avatar answered May 16 '26 10:05

TurtleTread



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!