简体   繁体   中英

Angular.js: Create 2 html containers using ng-repeat

I have a list of items, and I'd like to split each half of the items in it's own container.

How can I accomplish this using ng-repeat ?

<div>
    <ul>
        <li>Some item</li>
        <li>Some item</li>
        <li>Some item</li>
        <li>Some item</li>
        <li>Some item</li>
        <li>Some item</li>
    </ul>
</div>
<div>
    <ul>
        <li>Some item</li>
        <li>Some item</li>
        <li>Some item</li>
        <li>Some item</li>
        <li>Some item</li>
        <li>Some item</li>
    </ul>
</div>

Solution 1 : call slice on the collection

We can call the slice method on the collection :

<div ng-app="myApp" ng-controller="DemoCtrl" ng-init="half = numbers.length / 2">
    <div>
        <ul>
            <li ng-repeat="number in numbers.slice(0, half)">{{number}}</li>
        </ul>
    </div>
    <div>
        <ul>
            <li ng-repeat="number in numbers.slice(half)">{{number}}</li>
        </ul>
    </div>
</div>

See fiddle


Solution 2 : use limitTo built-in filter

<div ng-app="myApp" ng-controller="DemoCtrl" ng-init="len = numbers.length">
    <div>
        <ul>
            <li ng-repeat="number in numbers | limitTo: len / 2 + (len % 2)">{{number}}</li>
        </ul>
    </div>
    <div>
        <ul>
            <li ng-repeat="number in numbers | limitTo: - len / 2">{{number}}</li>
        </ul>
    </div>
</div>

The fact that we add len % 2 is for dealing with array oddity.

See fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM