AngularJS ng-repeat items do not properly align when utilizing Bootstrap col-md-2 styles

Utilizing AngularJS ng-repeat for displaying a list of products and incorporating bootstrap col-md-2 to showcase 6 products in each row, I have included a condensed version of my code below:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of Bootstrap 3 Grid System</title>
<link rel="stylesheet"   href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap- theme.min.css">
<script    src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js">    </script>
<style type="text/css">
    p{
    padding: 50px;
    font-size: 32px;
    font-weight: bold;
    text-align: center;
    background: #f2f2f2;
}
</style>
</head>
<body>
<div class="container">
    <div class="row">
       <div class="col-md-2" ng-repeat="item in items">
           <img src="{{itme.imgURL}}" />
           <p>{{item.title}}</p>
           <div>
                <a href="{{item.productURL}}" />
           </div>
       </div> 
    </div>
</div>
</body>

Some product titles are lengthy, causing them to span multiple lines and disrupt the alignment of elements. To observe this misalignment, please test the following code:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of Bootstrap 3 Grid System</title>
<link rel="stylesheet"   href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap- theme.min.css">
<script    src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js">        </script>
<style type="text/css>
    p{
    padding: 50px;
    font-size: 32px;
    font-weight: bold;
    text-align: center;
    background: #f2f2f2;
}
</style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-2"><p>Box 1 test</p></div>
        <div class="col-md-2"><p>Box 2</p></div>
        <div class="col-md-2"><p>Box 3</p></div>
        <div class="col-md-2"><p>Box 4</p></div>
        <div class="col-md-2"><p>Box 5</p></div>
        <div class="col-md-2"><p>Box 6</p></div>
        <div class="col-md-2"><p>Box 7</p></div>
        <div class="col-md-2"><p>Box 8</p></div>
        <div class="col-md-2"><p>Box 9</p></div>
        <div class="col-md-2"><p>Box 10</p></div>
        <div class="col-md-2"><p>Box 11</p></div>
        <div class="col-md-2"><p>Box 12</p></div>
    </div>
</div>
</body>
</html>  

In this scenario, Box 7 appears below Box 2 instead of being aligned under Box 1.

Although adding a clearfix div before Box 7 or placing elements 7-12 in a new bootstrap row can resolve the issue, due to using ng-repeat, individual control over each element is limited.

If anyone has suggestions on achieving proper alignment of all elements, it would be greatly appreciated!

Answer №1

If you want to implement a custom directive that will be executed for each item in a repeat loop, with the setTimeout() function used when reaching the last item to allow time for rendering of the HTML content and calling a height retrieval function, here is an example:

angular.module('box').directive('myRepeatDirective', function () {
    return function (scope, element, attrs) {
        if (scope.$last) {
            setTimeout(function () {
                scope.$eval('resizeBoxes()');
            }); 
        }
    };
})

The resizeBoxes method uses JQuery to determine the maximum height of elements and then sets all paragraphs to have the same height.

.controller("boxController", ['$scope', function ($scope) {
    $scope.boxes = boxes;

    $scope.resizeBoxes = function () {
        var maxHeight = -1;

        $('.col-md-2 p').each(function () {
            maxHeight = maxHeight > $(this).height() ? maxHeight : $(this).height();
        });
        $('.col-md-2 p').each(function () {
            $(this).height(maxHeight);
        });
    }
}])

HTML structure:

<div class="container" ng-controller="boxController">
    <div class="row">
        <div class="col-md-2" ng-repeat="b in boxes" my-repeat-directive>
            <p>{{b.label}}</p>
        </div>
    </div>
</div>

To view the code running, visit Plunker

Answer №2

Check out this helpful fiddle. Remember to include the necessary code in your project for it to work effectively.

This JavaScript solution was derived from a personal project experience where I encountered a recurring issue. I've considered turning it into a module because many developers face similar challenges.

The sizesiblings function takes a jQuery selector and ensures that elements maintain uniform dimensions based on the tallest element's height.

Here's an example of how you might use it...

I initially tried to explain it here, but it became too complex. Instead, I made updates to the fiddle :)

By calling

sizesiblings('.repeated-items>.col-md-2');
, all the divs should align properly.

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

Is there a way to ensure that all elements on a page display properly across all screen resolutions without being cut off?

My website consists of three main elements: pictures, Cards (containing pictures and various typography), and Buttons. These elements are arranged in a column layout. The issue I am facing is that the pictures and buttons get cut off on the screen due to ...

How can I utilize customToJSON in Sails 1.0 within an Action2 function?

Currently, I am facing an issue with my user model that requires the implementation of a customToJSON method to remove the password field from the returned JSON object. Everything works fine when I include "responseType" in the "exits" with a value of "jso ...

How can we prevent floating li elements from overlapping the parent div element?

What could be causing the yellow stripe (#header) to disappear when I apply "float left;" to "#header ul li"? Despite setting a fixed size for "#header ul li", I anticipated that the list items would line up next to each other horizontally, not exceeding t ...

Limiting the Display of Pages with PHP Pagination

Requesting assistance with updating the code to display full records. In my current setup, I am fetching records from a database and showcasing them in groups of 5 per page using the following code snippet: $num_rec_per_page=5; if (isset($_GET["page"])) ...

AngularJS Unveiled: The Puzzle of ng-if's Digest Loop

I am experiencing an issue with an infinite loop when loading the view. The data is retrieved from an API using ngResource in the controller. The view is being rendered multiple times before displaying correctly. I suspect that there may be a loop occurrin ...

How can I assign a value to an invalid input from a controller in AngularJS?

Just starting out with Angular and tackling my first full web application using it. I have a form that includes a required field. Because of this, I know the bound ngModel value will be undefined. The user has the option to either enter the value manually ...

Recurly.js version 3 with additional features

I'm currently exploring the functionality of addons in Recurly.js v3. For my form, I've linked a recurly.Pricing instance and added a checkbox for an optional addon: HTML <label for="plan-mobile" class="checkbox"> <input type="check ...

How can I center a text element vertically within its parent div element?

After researching various solutions to align text within a div, I have found that many recommend using the vertical-align property. Despite trying this method, it does not seem to work for my specific case. .free { display: inline-block; -webkit-bor ...

Receiving error message "51 F02 FacebookConnectPlugin sClass not found" while attempting Facebook login with Ionic and Cordova

I have been working on integrating Facebook login into my application. I followed the steps outlined in this Ionic blog: "". However, I am facing an issue where the login process is failing at $cordovaFacebook.login and not proceeding further. $scope.fb ...

Manipulate inherited CSS styles from an external source

Currently, I am working on creating a pagination using the NG-Bootstrap pagination component. However, I encountered an issue where I need to modify or specifically remove some CSS properties that are applied by default in the NG-Bootstrap library. Is ther ...

What is the best way to implement a dynamic sidebar component using React and Material UI?

I have been attempting to implement a responsive sidebar using React Material Design, but I am struggling to achieve the desired outcome. The main goal is for the page content to remain responsive when the sidebar is opened, without overlapping on the pag ...

Using QuerySelector with Angular Directive will throw an error as it is not a recognized

When creating a directive that integrates a jQuery carousel, I want to hide it at the beginning until it is fully ready. Here's the directive code snippet: return { restrict: 'E', replace: true, scope: true, templateUrl: ...

Replace particular letters within the text with designated spans

Suppose I have this specific HTML code snippet: <div class="answers"> He<b>y</b> <span class='doesntmatter'>eve</span>ryone </div> Additionally, imagine I possess the subsequent array: ['correct' ...

Enhancing the tooltip inner content in Bootstrap with a description:

Can you help me troubleshoot the code below? I am trying to add a description to numbers in my tooltip, but it doesn't seem to be working. Here is the HTML: <input id="contract-length" class="slider slider-step-2 slider-contract-length" ...

How to apply styling to a specific portion of text within a list element using Vue.js

Despite my best efforts, I am struggling to style only the word "healthy" within the 'It is healthy!' string using computed properties, watchers, and methods in vuejs. I'm at a loss for how to achieve this unique styling. <template> ...

Remove the content located beside an input element

Seeking assistance for a straightforward query: Snippet of code: <span> <input id="elemento_20_1" name="elemento_20_1" class="elemento text" size="2" maxlength="2" value="" type="text"> / <label for="elemento_20_1">DD</label> < ...

Firefox and Internet Explorer have a tendency to break lines at very specific pixel measurements

Hey, I have a situation that goes like this: I have 4 objects with dimensions of exactly 76x76px placed within a 320px container. This setup seems to work well in Chrome as seen above. However, in Firefox and IE9, it looks like this: even though the < ...

Tips for effectively utilizing innerHTML in this particular scenario

For an assignment, we were tasked with creating a Madlib game where users input words into textfields to replace certain words in a hidden paragraph within the HTML using JavaScript and CSS. The paragraph embedded in the HTML page is as follows: <span ...

Using several ng-repeats in a single element

Is it possible to create a code structure similar to this example: <tr ng-repeat="data in dataArray, value in valueArray"> {{data}} {{value}} </tr> I have two arrays that I would like to display on the same row. PS: I'm not see ...

FadeOut Television static on Canvas after a period of inactivity

Is there a way to smoothly fade out the TV noise after a specific timeout period? I found this code snippet on Stack Overflow that seems to address a similar issue: var canvas = document.getElementById('canvas'), ctx = canvas.getContext( ...