Utilize Angular to enclose columns within rows for optimal organization

Updated with angular code snippet (for demonstration purposes only)

I have been exploring ways in AngularJS to automatically wrap columns into rows after a certain number of columns while keeping the index intact.

<div class="row">
{{for (var i = 0; i < list.length; i++ )  {   }}
<div class="col-4">list[0].name</div>
{{  }  }}

Here's an equivalent approach in PHP:

To summarize:

<div class="row">
<?php 

 $collection = array( 'item1', 
                      'item2',
                      'item3', 
                      'item4',
                      'item5',
 );

 for($i = 0; $i < count($collection); $i++ ) : ?>

    <div class="col-4">
       <?php echo $collection[$i] ?>
    </div>

<?php if(($i + 1) % 3 === 0) :?>

</div> <!-- close row -->
<div class="row"><!-- open new row -->

<?php endif ?>
<?php endfor ?>

</div> <!-- close final row -->

I am aware that this can be achieved within a controller and then injected back into the DOM through a link function, but this approach seems less than ideal. I feel like there might be a better way, but I am struggling with conditionally adding the closing div before the opening one.

P.S. While I considered using Underscore.js for the example, I opted for a more universal solution.

Answer №1

(Taken from my previous responses.) This issue pertains to CSS specifically, rather than PHP or Angular; although solutions can be found within those realms.

Given that you are utilizing a flex-box framework, it is important to configure your rows with flex-wrap: wrap (ideally through a CSS file) and specify your columns as 33.33333% wide; in the context of Ionic, this translates to class='col-33'

Answer №2

Here's a unique approach to achieving a result similar to PHP output by utilizing ng-repeat, ng-if, and the special property $index. While this method may not be ideal due to generating empty elements, it does showcase the capabilities of ng-repeat.

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.collection = [
    'item1',
    'item2',
    'item3',
    'item4',
    'item5',
    'item6',
    'item7',
    'item8'
  ];
});
<body ng-controller="MainCtrl">
  <div ng-repeat="item in collection">
    <div class="row" ng-if="$index%3==0">
      <div class="col-xs-4">
        {{collection[$index]}}
      </div>
      <div class="col-xs-4">
        {{collection[$index+1]}}
      </div>
      <div class="col-xs-4">
        {{collection[$index+2]}}
      </div>
    </div>
  </div>
</body>

http://plnkr.co/edit/oytUy9rOkHmbFYowiINA?p=preview

For comparison, here is how the code looks when using flex:wrap:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.collection = [
    'item1',
    'item2',
    'item3',
    'item4',
    'item5',
    'item6',
    'item7',
    'item8'
  ];
});
<body ng-controller="MainCtrl">
  <div class="row" style="flex-wrap : wrap;">
    <div class="col-33" ng-repeat="item in collection">
      {{item}}
    </div>
  </div>
</body>

http://plnkr.co/edit/ZnzVJxQPzrxwSbes06RF?p=preview

Answer №3

It turns out that implementing flex-wrap: wrap; (as recommended by Carl Bussema) doesn't produce any results in the Ionic Viewer and iOS emulator (I haven't tested it on an actual device yet, but I anticipate similar outcomes).

To address this issue, I revisited some older code that resembled Claies' solution above. In order to prevent empty divs, I added an ng-if statement to check if the collection's length has reached the $indexed item.

<body ng-controller="MainCtrl">
    <div class="row" ng-repeat="item in collection" ng-if="$index % 3 === 0">
       <div class="col col-33" ng-if="$index < collection.length">
           {{collection[$index]}}
       </div>
       <div class="col col-33" ng-if="$index + 1 < collection.length">
           {{collection[$index + 1]}}
       </div>
       <div class="col col-33" ng-if="$index + 2 < collection.length">
           {{collection[$index + 2]}}
       </div>
    </div>
</body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Parse the HTML document using an HTTP request to access the Document Object Model (DOM)

I am facing an issue with accessing elements of an HTML page through JavaScript. I have tried different methods, but I keep getting the error message: CORS header "Access-Control-Allow-Origin" missing. Here is the code snippet I tried: <!DOCTYPE html&g ...

Can dynamic CSS imports be unloaded in a React application?

I am facing an issue with loading two files using react.lazy and suspense: import React, { Suspense, lazy } from "react"; import { Route, Redirect } from 'react-router-dom'; const MainLayout = lazy(() => import('Components/Layout/MainL ...

replace icons using AngularJS app.directive

I am facing an issue with my menu icons. When I click on one icon, it changes as expected. However, if I click on another icon, the first one should return to its original state but it doesn't. I am not sure why this is happening. Below is the HTML c ...

In ReactJS, when passing an array of objects to a child component, the first instance may sometimes return as undefined, causing the code to break

Currently, I am in the process of creating a personal blog for my brand. The "Posts" section is designed to retrieve data from a basic JSON via an API. At present, I have used mirageJS to mock the API and employed the useEffect and useState hooks to set th ...

I am experiencing difficulties with broadcasting and attending events

File.js scope.menuItemClick = function (def, callbackText, keepMenuOpen) { console.log(def); if(def.automationId === "Print"){ console.log("before send"); $scope.$root.$broadcast("printingData","my Data"); console.log("after send"); } Nex ...

Troubleshooting the issue with a styled subcomponent in React using Styled Components

Recently, I've delved into React and have been experimenting with creating a Modal component using styled components. My goal is to achieve a similar effect to Framer Motion's motion.div, but utilizing styled components instead. Currently, I hav ...

ng-repeat binding stops working when using Parse.Cloud.run()

Explaining the problem at hand: utilizing AngularJS version 1.3.15 incorporating the Parse.com library version 1.4.2 the onscreen output linked to my controller isn't updating when the underlying structure undergoes updates The HTML code is straigh ...

"Learn the process of integrating Javascript files from the Angular assets folder into a specific Angular component or module (such as Angular 2, 4,

I have custom1.js, custom2.js, and custom3.js JavaScript files that I need to load into Angular components component1, component2, and component3 respectively. Instead of adding these files to the index.html globally, I want to load them specifically for e ...

The conflict between ESLint's object curly new line rule and Prettier's multi-line formatting

I'm brand new to the world of prettier, typescript, and eslint. Even though most of the integration is going smoothly, I am facing an issue with multi-line destructuring objects. Prettier Version 1.19.1 Playground link Input: const { ciq, draw ...

To ensure a rectangular image is displayed as a square, adjust its side length to match the width of the parent div dynamically

How can I make the images inside my centered flexbox parent div, #con, be a square with side length equal to the width of the parent div? The image-containing div (.block) is positioned between two text divs (#info and #links). I want the images to be squa ...

Regular expression to detect a space that is escaped

Given a string: rsync -r -t -p -o -g -v --progress --delete -l -H /Users/ken/Library/Application\ Support/Sublime\ Text\ 3/Packages /Users/ken/Google\ Drive/__config-GD/ST3 Attempting to find a regex pattern that matches spaces, but ex ...

What is the best way to limit the character display to a maximum of 30 in Vue.js?

My current goal involves achieving the following task. In a certain variable, I currently have this text: let text = 'hey this is a super long phrase' I am looking to utilize a label to showcase the text, but with only a limited number of char ...

Undefined scope

angular.module('CrudApp', []). config(['$routeProvider', function($routeProvider) { $routeProvider. when('/', { templateUrl: 'assets/tpl/lists.html', controller: ListCtrl }). when('/add-user&apos ...

Meteor push/browserhistory fails to navigate or refresh to a different page

Currently, I am attempting to set it up so that when a user clicks on a profile, they are redirected to the profile page of the user they clicked on. Here is the code I am using: const self = this; browserHistory.push({ pathname: '/user ...

Trouble arises when jquery's "position().top" clashes with the CSS3 property "transform: scale()"

Currently, I am working on adding a font resizer feature to my editing tool. To implement this, I made some changes to the text elements where their origin is now set to the bottom left corner. The normal version of the tool works perfectly fine, but when ...

Error: JQuery AJAX call caused an unhandled RangeError due to exceeding the maximum call stack size

I am facing an issue with a jQuery ajax call. Interestingly, when I comment out the ajax call, everything works perfectly fine. It passes all validations and enters the 'else' part which contains the ajax call. Strangely, if I include an alert by ...

Utilizing CSS Media Queries to Activate DOM Alterations

Utilizing CSS media queries, I am able to display different layouts of my website based on the width of the screen. This involves showing and hiding specific elements accordingly. However, in addition to this, I also need to rearrange elements within the ...

Converting to JSON can be done dynamically by adjusting the format based on the size of an array

Below is the flat array I have: let data = [ ["0000001", "PAUL", "Y", "PELUCHE", "DRAKE", "DOG"], ["0000002", "ECHEBEL", "Y", "CAT", ""], ...

Filtering Quantity Based on Specific Attribute in ReactJs

I want to implement a quantity filter that can be based on color, size, or both. For instance, when I select the red color, it should display the total quantity of red items available. However, if I choose both the color red and size small, it should show ...

Adjust the x-axis on the Vue.js bar chart

I'm currently working on a Vue.js Laravel application where I am trying to incorporate a bar chart using the ApexCharts module. <apexchart ref="apexChart" :options="chartOptions" :series="chartData" type="bar" ...