How can I dynamically set the width of a span element in HTML?

Hello there! As a beginner in html and angularjs, I'm experimenting with dynamically assigning span width based on an angular js response.

<div class="statarea" ng-repeat="x in names">
     <div class="ratingarea">
        <div class="your-rating"><span style="width:"+{{ x.width }}+";" class="outer"></span>
        </div>
     <div class="clear"></div>
     </div>
</div>

Here's a snippet of my script:

$http.get(url).success(function (response) {
  $scope.names = response;
});

The response data looks like this:

[
 {"width":"78%"},
 {"width":"60%"},
 {"width":"50%"}
]

I realize it may not be perfect, but I'm learning as I go. Any tips would be greatly appreciated!

Answer №1

To style elements dynamically in Angular, you can utilize the ngStyle directive. This directive allows you to set CSS styles based on conditions or variables.

For example, you can use the following syntax: ng-style="{color: myColor}"

The ngStyle directive requires an Expression, which evaluates to an object with CSS style names as keys and their corresponding values. To set styles dynamically within a loop, you can do something like this:

<div class="statarea" ng-repeat="x in names">
  <span ng-style="x" />
</div>

You can also use scope variables for dynamic styling:

<div class="statarea" ng-repeat="x in names">
  <span ng-style="{'width': x.width}" />
</div>

Answer №2

To achieve this, you would need to utilize ng-style. You can view an example of this in action on JSFiddle here

<div ng-app="" ng-init="names = [{width:'78%', 'background-color': 'green'},{width:'60%', 'background-color': 'red'},{width:'50%','background-color': 'blue'}]">
<div class="statarea" ng-repeat="x in names">
     <div class="ratingarea">
        <div class="your-rating">
            <span ng-style="x" class="outer">{{x.width}}</span>
        </div>
    </div>
    <div class="clear"></div>
</div>

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

Learn about Angular8's prototype inheritance when working with the Date object

In my search for a way to extend the Date prototype in Angular (Typescript), I stumbled upon a solution on GitHub that has proven to be effective. date.extensions.ts // DATE EXTENSIONS // ================ declare global { interface Date { addDa ...

One of my AngularJS directives seems to be malfunctioning while the rest are working fine. Can you help me troubleshoot

Recently, I've been immersing myself in the job search process and decided to create a website as a sort of online resume while also learning AngularJS. I enrolled in the Angular course on CodeSchool and am slowly building my website to my liking. (Pl ...

Using jQuery to create a nested table

I have a table that I would like to customize so that when a user clicks on a row, only the child table under that specific row is visible while the child tables under other rows are hidden. How can I achieve this using jQuery? <table class="mainTabl ...

My desire is for every circle to shift consecutively at various intervals using Javascript

I'm looking to draw circles in a sequential manner. I am trying to create an aimbooster game similar to . Instead of drawing all the circles at once, I want each circle to appear after a few seconds. The circles I've created currently do not g ...

Verification of javascript for an unpredictable image generator script

When running the W3C Validation tool, an error is returned stating 'img not acceptable here.' Any suggestions on how to resolve this issue? <script type="text/javascript" language="JavaScript"> NumberOfImagesToRotate = 9; FirstPart = &ap ...

Issue with text-nowrap not functioning as intended within Bootstrap 4.5 table cells

Is there a way to eliminate the space between two columns in my layout? I want to get rid of the highlighted space below. I attempted using text-nowrap, but it didn't achieve the desired result. <link href="https://stackpath.bootstrapcdn.co ...

Strikeout list on click of a mouse

Is there a way to apply strikethrough formatting to text with just a mouse click? The CSS for lists is beyond the form field margin. I've tried multiple methods without success. No matter how many times I change the code, I can't seem to get it r ...

Adding a gap between the Bootstrap navbar and jumbotron for better spacing

Upon examining the Bootstrap example provided at: http://getbootstrap.com/examples/navbar/ I noticed there is a gap between the jumbotron and the navbar. After delving into the example's CSS, I found that disabling this rule (twice): .navbar { ...

Adding margin padding to a Material UI Navbar: Step-by-step guide

Hey there, I've added buttons to my Navbar from Mui. However, I'm running into an issue where the margin and padding won't change no matter what I do. I'm trying to create some space between them. Please see the code below: import { use ...

Utilizing the CSS Top and Left attributes along with Jquery animations

There are two divisions on a page, namely Left_Div and Right_Div. The images in the Right_Div are positioned using CSS properties such as Top and Left. The Left_Div acts as a left panel, and upon clicking a button, both Left_Div and Right_Div animate to sl ...

Eliminate the bottom border from the MUI Input component

Is there a way to get rid of the bottom-line borders on these input fields? I attempted using CSS but couldn't find a solution for this component -> <Input type={"text} /> ? ...

What could be causing the JavaScript array to not successfully transfer to PHP?

Despite searching for solutions, I am unable to get the desired outcome. When I check my JavaScript array in the console, it appears like this: [] 0:Object stock:27 createdtime:"2016-04-08T04:00:00+0000" id:"693852404037393999" units:438 ...

Storing large data tables in C#: Tips for efficient caching

Currently, I am facing the challenge of executing a lengthy PL/SQL query and storing the result set in order to serve UI requests. Additionally, I need to refresh this data automatically or manually after some time. The complexity arises from handling mult ...

Tips for efficiently finding and comparing text within the results generated by a for loop in Angular/Javascript

In my XML data, I have extracted all the tag names using a for loop and some other logic. Now, I am looking to find the word 'author' from the output values that are displayed in the console during the loop. If any of the output values match &apo ...

Even in the face of errors, Selenium with Node.js continues to run seamlessly. The challenge arises specifically with the 107.xx version of the Chrome browser and Chrome driver

Currently, I am employed in a project involving NODE JS (javascript) with selenium webdriver. Package.json- “chai”: “^4.3.6”, “chromedriver”: “^107.0.3”, “geckodriver”: “^3.2.0”, “mocha”: “^10.0.0”, “mochawesome”: “^7. ...

Is it possible to display multiple qTips for the same target using jQuery qTip2?

I am currently utilizing the jquery qtip2 plugin to generate a mouseover tooltip. Here is the code snippet I am using: $(document).ready(function() { $("#optionalProdsImgPreview_1").qtip({ content: "<img src='http://mysite.com/myimg.jpg&ap ...

When the onclick function is triggered, two or more characters will be displayed

Functionality: To input name and email, users must click on the virtual keyboard displayed on the screen. Characters entered will be shown in the input box. Implementation: The HTML keyboard interface and associated script have been developed successful ...

The specified element type is not valid: only a string (for built-in components) or a class/function is expected when attempting to display a component

`Unhandled Runtime Error Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you mi ...

Guide to generating a graph using PHP and quickcharts

I am working with a dataset that looks like this: Timestamp Value Importance 5/22/2022 4:19 3245 0.0234 5/22/2022 4:09 3246 0.0214 5/22/2022 4:09 3247 0.1234 5/22/2022 3:59 3248 0.0534 5/22/2022 3:59 3249 0.1234 5/22/2022 3:49 ...

CSS grid tracks remain fixed in size while other tracks expand

Why won't the grid track cells dynamically shrink when other cells are enlarged in the following code? In this snippet, hovering over any track section causes that cell to grow to 75% of the viewpoint. However, instead of the other sections shrinking ...