how to adjust the width of table columns dynamically using ng-repeat and AngularJS

Working on a user interface that contains a table where the column widths adjust according to percentage data. I'm using ng-repeat to populate the table, but need help setting unique widths for each piece of data received. Here's some of my AngularJS code:

var App = angular.module("myApp", []);
App.controller("maincontroller",function($scope){
$scope.info=[
{name:'aob',
number:20%},
{name:'cc',
number:15%},
{name:'mb',
number:20%},
{name:'ts',
number:6%},
{name:'ws',
number:8%},
{name:'t',
number:8%},
{name:'aob',
number:2%},
{name:'pb',
number:25%}
]
});

This is an excerpt from my HTML file where I need to add dynamic data into the table while the other tables are hard-coded.

<!doctype html>
<html ng-app="myApp">
... (the rest of the HTML code)
</body>
</html>

Answer №1

Here is a slightly modified version of the code snippet provided:

<div ng-repeat="item in items">
   <p>{{item.name}}: <span style="width: {{item.value}};">{{item.value}}</span></p>
</div>

The values for "value" can be specified as percentages or pixels, whichever suits your needs.

In the controller, you would define the items like this:

$scope.items = [
    {name: 'item1', value: '70%'},
    {name: 'item2', value: '10%'},
    {name: 'item3', value: '20%'}
];

This structure should allow you to display each item with its respective width dynamically based on the assigned values.

Additionally, it's worth noting that in this version I have used inline styling with style="width: {{item.value}};" instead of the original use of ng-style="" for achieving similar functionality.

Answer №2

One strategy could involve creating a specialized directive for either columns or rows, depending on your preference. This directive would replace the standard row or column with a customized version generated within the directive and tailored to specific width criteria. This concept is illustrated using a td element as an example, but can be adapted as needed. I trust this explanation proves helpful.

angular.module('appname')
    .directive('tddirective', ['$compile',
        function ($compile) {
            return {
                scope: {
                    item: '='
                },
                replace: true,
                link: function (scope, element, attrs) {
                    var html = "";

                    function addElement(html) {
                        var toInsert = angular.element(html);
                        element.append(toInsert);
                        $compile(toInsert)(scope);
                    }

                    //You can implement validation or define specific width requirements here, possibly comparing with other columns and adjusting formatting accordingly
                    html = '\
                           <td style="width: " + item.width +";">item.name</td>';
                    addElement(html);
                 }
            }
        }])

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

Assistance needed with Jquery fade-in and fade-out effects

$('.HelpBoxOk').live('click',function() { var currentDiv = $(this).parent().parent().parent().parent().parent().parent(); var shouldFadeInNext = false; if($(this).attr('value') == 'Next') { ...

Is there a way to determine the file size for uploading without using activexobject?

Can the file size of an uploading file be determined using Javascript without requiring an ActiveX object? The solution should work across all web browsers. ...

Leverage the power of Angular 2 components within your Asp.net MVC

I am currently working on an Asp Mvc project which utilizes Angular 1.4 for the frontend. While my project is not designed to be a single page application, I am interested in incorporating Angular 2 without transitioning the entire project into a SPA. Aft ...

PHP: The constant ENT_HTML5 is not defined and has been assumed as 'ENT_HTML5'

I encountered the following error message: Use of undefined constant ENT_HTML5 - assumed 'ENT_HTML5' in /blahblahpath/application/models/Post.php on line 12 This error occurred in a basic model that handles some POST input in a forum applicatio ...

When converting to TypeScript, the error 'express.Router() is not defined' may

Currently, I am in the process of converting my express nodejs project from JavaScript to TypeScript. One of the changes I've made is renaming the file extension and updating 'var' to 'import' for "require()". However, there seems ...

"Encountering a restricted URI error when attempting to load a text file using AJAX

After reviewing the recommended link, I found myself struggling to grasp the suggestion to "Use Greasemonkey to modify Pages and start writing some javascript to modify a web page." Currently, I am encountering an error when loading a text file using $.aj ...

Customizing Marker Clusters with ui-leaflet: A guide on changing marker cluster colors

I'm trying to customize the markerCluster color in a non-default way. I've been exploring the API and it looks like the recommendation is to modify a divIcon after creation, possibly like this: var markers = L.markerClusterGroup({ iconCreateFunc ...

Interactive Google Maps using Autocomplete Search Bar

How can I create a dynamic Google map based on Autocomplete Input? Here is the code that I have written: <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDeAtURNzEX26_mLTUlFXYEWW11ZdlYECM&libraries=places&language=en"></scri ...

Utilize Require.js to Load Dropzone.js Library

I am interested in integrating Dropzone.js into an application that is built using Backbone and Require.JS. However, I am unsure of the correct implementation process. Should I utilize require()? What is the most effective way to handle this integration? ...

What purpose does generating a JSON file serve when invoking getStaticProps in Next.js?

Just diving into the world of Next.js. I've been going through the Next.js documentation and stumbled upon this: Next.js creates a JSON file that contains the outcome of executing getStaticProps. This JSON file is used in client-side routing via nex ...

The NgModel function within *ngFor is executing more times than necessary during initialization

Displayed on screen are a list of tutorials with check boxes next to each tutorial's states. These tutorials and states are pulled from the database, each tutorial containing a name and an array of associated states. Here is the HTML code: <div c ...

Adjust regex for image URLs in JavaScript to handle unique and special cases

Does anyone have experience with using image URL regular expressions to validate images in forms with the ng-pattern directive? I'm currently facing difficulties handling cases like https://google.com.png. Any assistance would be greatly appreciated. ...

Listening for server updates with jQuery

I am currently working on a web application that communicates with a server for database updates. The issue I am facing is that the update process can vary greatly in time, ranging from milliseconds to tens of seconds for larger updates. I would like to im ...

Following the modification of the Context root, the JSP page is no longer functioning as expected

Recently, I developed a JSP page within the webapp that utilizes jquery, CSS, and Angular JS. The files jquery-1.12.0.js, angular.min.js, and TableCSSCode.css are all located in the same directory as the JSP page. Initially, my application context was set ...

What is the process of invoking a JavaScript function from Selenium?

How can I trigger a JavaScript function from Selenium WebDriver when using Firefox? Whenever I am logged into my website, I typically utilize this command in Firebug's Command Editor to launch a file upload application: infoPanel.applicationManager. ...

Retrieving Vue data from parent components in a nested getter/setter context

<template> <div id="app"> {{ foo.bar }} <button @click="meaning++">click</button> <!--not reactive--> <button @click="foo.bar++">click2</button> </div> </templ ...

"Upon the second click, the Ajax success function will display the returned view

When using a post request in angular's factory with ajax, everything seems to be working fine except for the success function. Upon clicking the login button, it seems like I have to click it twice to navigate to another page (logout.html). I'm n ...

ImageMapster for perfect alignment

I'm struggling with centering a div that contains an image using imagemapster. When I remove the JS code, the div centers perfectly fine, indicating that the issue lies with the image mapster implementation. It's a simple setup: <div class=" ...

Unveiling the hidden: Leveraging Python to extract elements not visible in HTML, yet present in Chrome's "Inspect Element" tool

Hello Python Experts! I'm diving into the world of Python and working on a program to retrieve data from a webpage. If the page returned all the information in its HTML source, there wouldn't be an issue as it's easily viewed in Chrome. Howe ...

Does setting white-space:nowrap enlarge the div?

My CSS code for div .name sets the width to 75% to truncate text if it doesn't fit. However, resizing the window causes the text to remain the same size and my entire website structure falls apart. This is the HTML code snippet: <tr> <t ...