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

Steps for allowing the cells in a Data-Table column to be edited

Is it possible to have editable cells in a column of a Data Table with the support of the plugin? ...

React: the props appear to be undefined when they should actually have a value

I have a requirement for my props in the children class to be an array of Event objects. Prior to using it in App.js, I am checking if the array is empty like this: function App() { class Event { constructor(id, title, date){ this.id = id; ...

I am looking to pair a unique audio clip with each picture in my collection

I have implemented a random slideshow feature that cycles through numerous images. I am now looking to incorporate a brief audio clip with each image, synchronized with the array I have established for the random pictures. The code snippet below is a simil ...

Having difficulty positioning the dropdown above the other elements in the body

Below, you'll notice that the dropdown menu isn't positioned correctly over other body elements like the timer. I'm utilizing bootstrap for the dropdown and redcountdown js for the timer. Here is the HTML: <div class="col-md-6 m-t-1 ...

There is an error message in Vue nextTick: "TypeError: this.method is not a function." The error only appears in my console, but the functionality seems to be working correctly in the browser

I'm experiencing an issue where I encounter an error when accessing a certain component for the second time in my browser. The strange thing is that everything appears to be working fine initially, but the error occurs when I try to perform actions li ...

Learn the process of generating sequential heading numbers for topic headings in each HTML document using DTA or XHTML

I attempted to include hierarchical numbers for topic headings in dita2xhtml_eclipsehelp.xsl. (DITA OT HTML output) However, I am facing difficulty in producing numbers similar to the following in each html file: 1 heading text 1.1 heading text 1.1.1 Head ...

The extended class possesses a distinct type from the base class, which is reinforced by an interface

Is it possible to write a method that is an extension of a base class, but with a different return type, if supported by the shared interface, without adding a type declaration in class 'a'? In practical terms, classes a & b exist in JavaScript ...

Is it possible to create a route in AngularJS that displays multiple views at once?

Imagine a scenario in which we have a specific route, let's call it myapp\profile, with two different modes (buyer/seller). Here is what I am aiming to accomplish: Maintain the same route URL for both modes. Switch between views using different ...

Following the execution of the "ng build --prod" command in Angular 2, the functionality of ui

Utilizing an Angular program with a Node.js server and the ng serve command has been successful. However, when attempting to transfer this code to a shared Linux server and using XAMPP for compilation, an error was encountered: ng build --prod The error ...

Convert the $rootScope object to a JSON string

In my web application, I am working on incorporating a basic bug-tracker feature. I ask the user to provide a written description of the issue, and then I aim to include a JSON version of $rootScope (values) that I will transmit using $http. Any suggesti ...

Guide to defining API elements in Bootstrap 5 modal

I have been struggling with this issue for quite some time. I am working on a movie app and trying to implement a modal feature. Currently, I am able to display each movie individually along with their poster, title, and score. The goal is to have the mod ...

The callback function for ajax completion fails to execute

My current framework of choice is Django. I find myself faced with the following code snippet: var done_cancel_order = function(res, status) { alert("xpto"); }; var cancel_order = function() { data = {}; var args = { type:"GET", url:"/exch ...

Iframe displaying a blank white screen following the adjustment of document.location twice

I am in the process of developing a web application that I intend to integrate into my Wix website. The main components of the required web application are a text screen and a button to switch between different screens/pages (html content). However, I am ...

ng-repeat is not functioning as anticipated within a div on a table due to custom filtering of data

The provided template, which aims to display a traditional year planner style calendar with a div for each year and a table for each month, is not functioning correctly as expected. <div ng-repeat="year in calendar | ToCalendar"> {{year.name}} & ...

Switch the class on a specific div section

As you scroll to the top, a class named "blue" is added to the element with the ID of "div". However, when the scroll returns to the bottom, the "blue" class remains without being removed. Fiddle Link: http://jsfiddle.net/5d922roc $(window).scroll(fu ...

When the file is active on a local machine, the bot commands run smoothly. However, these commands do not execute on a remote

Lately, while working on coding a discord bot using discord.js, I came across an issue. Whenever I run my bot on my local machine, all the commands work perfectly fine. However, after committing and pushing the code to GitHub, and then allowing buddy.works ...

Is it possible to create two custom WP queries that both use the same 'rand' parameter with the 'orderby' set to 'rand'?

My homepage currently displays 9 posts with a "Load More" button that fetches another 9 posts using ajax. The posts are ordered by date, but I want to change the order to random. However, when I use orderby rand in two wp_query instances, the second query ...

Unsuccessful attempt at implementing knockout data-binding on a dynamic webpage utilizing the Hot Towel API

I'm facing an issue while trying to bind knockout data to a dynamically generated input field. To briefly explain the canActivate(id) function, it retrieves details of all necessary objects for the page and stores them in vm.OPCLayoutVm. ...

Retrieve information from the Next API within the getStaticProps function in a Next.js project

In my Next.js project, I encountered an issue where fetching data in getStaticProps() worked perfectly during local development but resulted in an error during next build. The error indicated that the server was not available while executing next build. Fe ...

Shifting a div from side to side

I don't have much experience with coding, so I was hoping for some assistance. My goal was to create a div that moves back and forth using toggleClass; $('div').on('click', function() { $(this).toggleClass('active') ...