Generate random div elements and insert them dynamically into a fixed-sized container using AngularJS. The number of div elements created can range anywhere from 0 to

Within a div of fixed size, dynamically generated div elements are displayed using ng-repeat. The inner divs should adjust their size to accommodate the number of child divs present - for example, if only one div is present, it should take up 100% of the space; if two divs are present, each should take up 50%. I have attached a screenshot for reference. Thank you in advance.

Answer №1

Styling with CSS

.large{

     height: 300px;
     width: 300px;
     overflow: auto;
     background: #DAE8ED;

}

.small{
    float:left;
    background: #EDDFDA;
}

Controlling the Style,

app.controller('Ctrl', function($scope){

  $scope.numbers = [1,2,3,4,5,6,7];
  var size = 300/Math.ceil(Math.sqrt($scope.numbers.length)) + 'px';
  $scope.customStyle={'height':size, 'width':size};
});

Creating the Layout in HTML,

<body ng-controller='Ctrl'>
    <div class='large'>
     <div class='small' ng-repeat="n in numbers" ng-style='customStyle'></div>
</div>

Answer №2

If you want to dynamically change the CSS class of a div based on the number of div elements, you can use ng-class.

Start by creating different CSS classes with a container.

CSS

.container{
  width:400px;
  height:400px;
  border:solid 1px black;  
}

/* apply to all child */
.child{
  display:inline-table;
}

/* For a 2x2 layout */
.two{
  background-color:red;
  width:50%;
  height:50%;
}

/* For a 3x3 layout */
.three{
  background-color:blue;
  width:33.3%;
  height:33.3%;
}

/* For a 4x4 layout */
.four{
  background-color:yellow;
  width:25%;
  height:25%;
}

HTML

<div class="container">
       <div ng-repeat="item in items" class="child" ng-class="{'two':(items.length<=4),'three':(items.length>4 && items.length<=9),'four':(items.length>9)}">
       {{item}}
       </div>
  </div>

Feel free to modify the array in the example above to see how it affects the layout.

Check out this JSFiddle Example for reference

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

The issue of asynchronous nested callbacks not functioning properly within each iteration of a for loop in Node.js

I have been using the code snippets below to retrieve followers of a specific user stored in mongodb. Here is an example of a saved user JSON: { "_id":{ "$oid":"5440f606255cd4740e88ed21" }, "username":"test2", "email":"test2%40gmail.com", " ...

Is it possible to change the button class within a div while ensuring only the last one retains the change?

Here is a code snippet I'm using to switch between classes for buttons: $('button').on('click', function(){ var btn=$(this); if(btn.attr('class')=='tct-button'){ btn.removeClass('tct-button ...

What could be causing the 405 error in my post request?

While attempting to send a post request to Firebase through my Vue app, I keep encountering an error illustrated in this image. I have a webpack server running and the website is on localhost:8080. However, I also have a live version hosted on hostinger a ...

Select three random items from a string array list along with their corresponding indexes using TypeScript in Angular

Consider this example: I am working with a string array const groceries = [ 'milk', 'coriander', 'cucumber', 'eggplant', 'carrot', 'brinjal', 'on ...

Revamp the switch-case statement in JavaScript code

Is there a way to refactor this code in order to prevent repeating dailogObj.image? I would have used a return statement if it wasn't for case 5 where two assignments are required. getDialogData(imageNum): any { const dailogObj = { image: ...

Javascript's ReferenceError occasionally acts inconsistently when using Firefox's scratchpad

While delving into the world of Javascript for learning purposes, I encountered an unexpected behavior. Let's explore this scenario: function hello(name) { let greet = 'Hello ' alert(greet + name) } hello('world') alert(gree ...

Top method for handling multiple conditions - JavaScript

I created a customized function to create a responsive carousel with multiple images per slide. (Unfortunately, I couldn't get Owl Carousel to work on my Angular project, but that's not the focus here). The number of images displayed per slide i ...

Is there a way for me to determine which class has been selected using jQuery and JavaScript?

I created a list containing various links: <li class="link-1"><a href="#">One</a></li> <li class="link-2"><a href="#">Two</a></li> <li class="link-3"><a href="#">Three</a></li> .. Wh ...

Struggling to understand the relationship between SetInterval and closures

Is there a way to continuously update the contents of a div using setInterval I found inspiration from this question on Stack Overflow: How to repeatedly update the contents of a <div> by only using JavaScript? However, I have a couple of questions ...

javascript creating unique model instances with mongoose

I've searched through related posts without finding exactly what I need. Currently, I am working on building a backend rest API and conducting tests to collect data. Each test has its own model which is associated with collections in the database. T ...

What could be causing the unexpected behavior of req.query in NEXT.js?

In the latest version of NextJS App Router, I have the following code located in the file app\api\products\route.tsx import { initMongoose } from "@/lib/mongoose"; import Product from "@/models/products"; import { NextApi ...

Utilizing Jquery's .load function will temporarily deactivate all other functions

Season's Greetings everyone! I have a unique personal messaging system on my website that utilizes jQuery for message display and manipulation. Let's delve into the specific file that controls this functionality: <!-- Fetching and displaying ...

Use JavaScript to retrieve a value and display it on a PHP page

I am trying to create a system that can generate and deliver JSON data. Here is the PHP code I have so far: <?php header("Content-Type:application/json"); require "data.php"; if(!empty($_GET['name'])) { $name=$_GET['name']; ...

Issue with React container not connecting properly

I am currently facing an issue with a search bar where the input value is not displaying properly. Even when I check the value in the console, it only shows one character at a time. https://i.stack.imgur.com/Qm0Lt.png My assumption is that there might be ...

Utilize jQuery and PHP to populate an HTML Select Field with data retrieved from a MySQL Database in JSON format

I am exploring how to Transfer Database Data into an HTML Dropdown Selection Field using jQuery. I came across a useful example that seems promising. Although I am new to jQuery and JavaScript, I am eager to learn. My goal is similar to the approach descr ...

Run ajax function prior to changing location; status now marked as canceled

Imagine needing to redirect a page when a button is clicked: <div onClick="clickButton"></div> function clickButton(href) { // an HTTP post request is sent here, without a callback or then/done function sendSomeRequest() location.href ...

jquery events such as onSubmit, onComplete, etc. are commonly used

It's interesting to observe that many tools in jQuery, especially those involving ajax, contain hooks like onSubmit, onComplete, and more. Is there a specific term for this practice and the standards associated with it? Does this practice belong sol ...

The issue of the selection option not being cleared after being set to 0 persists in JavaScript

I am facing an issue where I need to reset the select option to `0` when another option is selected. I have tried the code below for this purpose. if (varALPO1MobNum == "0") { var selectElement = $(&apo ...

What is the process for creating a symbolic link from a project's node_modules directory?

Recently, I've been learning how to build a Password Manager using React, Node.js, and MYSQL by following a tutorial. However, I encountered an issue where the file /EncryptionHandler was located outside of the src/ directory of my project. Even thoug ...

Leveraging a nodejs script integrated with socket.io within an angular/electron hybrid application

I have successfully created an electron/angular app that is functioning well. Additionally, I have developed a nodejs script to open a socket.io server using typescript + webpack to generate all files in a bundled js file. My challenge arises when trying ...