AngularJS Loops and Formatting

very new to AngularJS so please forgive me if this is a stupid question.

I need to output my data in a grid like format (using Ionic) and i need to have a div for a row and separate divs for columns, like this

<div class="row">
    <div class="col-33">Item 1</div>
    <div class="col-33">Item 2</div>
    <div class="col-33">Item 3</div>
</div>
<div class="row">
    <div class="col-33">Item 4</div>
    <div class="col-33">Item 5</div>
    <div class="col-33">Item 6</div>
</div>

My data is within a list, much like this.

    $scope.images = [];
    $scope.images.push({text: 1});
    $scope.images.push({text: 2});
    $scope.images.push({text: 3});
    $scope.images.push({text: 4});
    $scope.images.push({text: 5});
    $scope.images.push({text: 6});

How can i use the $scope.images list to output my as a grid?

The closest i have got is below, but it doesnt work.

<ion-content>
    <div class="list list-inset" ng-init="myIndex = 0">

        {{myIndex }} : {{ images.length }}

        <div ng-repeat="myIndex < images.length" >

            <div class="row" ng-repeat="colIndex in [0, 1, 2]" ng-init="colIndex = 0">

                <div ng-show="myIndex + colIndex < images.length" class="col-33" ng-init="myIndex = myIndex + 1">

                    {{ myIndex }}:{{ colIndex }}:{{myIndex + colIndex}}:{{ images[myIndex + colIndex].text}}

                </div>

            </div>

        </div>

    </div>

</ion-content>

Is there such a thing as a while loop? I was hoping i could increase the $index variable if i used ng-repeat="item in images", but not sure how to do that either.

Thanks in advance

Answers:

Answer

Something like this? fiddle

<span style="float: left">{{item}}</span><br ng-if="($index+1)%3 == 0"/>

I simply break the line every three items, but we could expand on this approach.

Update with complete, working solution: fiddle

<div class="container">
    <div ng-repeat="item in items" ng-if="$index%3==0" class="row">
        <span ng-if="$index<items.length" style="float: left">{{items[$index]}}</span>
        <span ng-if="($index+1)<items.length" style="float: left">{{items[$index+1]}}</span>
        <span ng-if="($index+2)<items.length" style="float: left">{{items[$index+2]}}</span>
    </div>
</div>

The code is pretty self-explaining: the solution creates a row every three elements, and inserts the elements only if they actually exist.

Answer
<div class="row" ng-repeat="photo in photos" ng-if="$index % 3 == 0" ng-init="photoIndex = $index">
    <div ng-repeat="i in [0,1,2]" ng-if="(photoIndex + i)<photos.length" class="col-33">
        <img ng-src="{{photos[photoIndex+i]}}">
    </div>
</div>

Here is a more compact version of the above answer.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.