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

What could be causing the abortTransaction() method in mongoose to not function as

System OS: MacOS 10.15.5 NodeJS Version: 10.16.3 Mongoose Versions: 5.8, 5.9 MongoDB Version: 4.0.3 The following code snippet is in question: import User from 'models/user' const session = await User.startSession() session.startTransaction() ...

The automatic opening of a modal in a Livewire component is not functioning as expected

I am having trouble displaying a modal when my component initializes. I have tried using $this->emit('show) to open the modal When I add a button in my view, the emit('show') works! However, I want the modal to be automatically shown whe ...

Utilizing the NestJS Reflector within a Custom Decorator: A Comprehensive Guide

I have implemented a solution where I use @SetMetaData('version', 'v2') to specify the version for an HTTP method in a controller. Additionally, I created a custom @Get() decorator that appends the version as a suffix to the controller ...

Using Svelte to effectively connect to a specified object within an array

Check out this code snippet: <script> let data = [ {id: 1, first: "x"}, {id: 2, second: "y"} ]; </script> <input type="text" bind:value={data.first}/> If you modify the value in the input field and ...

Utilizing a dropdown list in HTML to dynamically change images

On my HTML page, I have implemented a dropdown list box. My objective is to change an image and update a label based on the selection made from the dropdown list box. I already have an array called 'temp' which represents the number of items. The ...

Tips on hovering over information retrieved from JSON data

Within my code, I am extracting information from a JSON file and placing it inside a div: document.getElementById('display_area').innerHTML += "<p>" + jsonData[obj]["name"] + "</p>"; I would like the abi ...

The Route.go function is ineffective when used in form submission

Hey there! I'm new to the world of meteor and javascript, currently working on a fun little app project. My tool of choice is meteor with ionic. Here's a snippet from my simple form: <form> .... <label class="item item- ...

Saving information to a hidden div using jStorage

Currently, I am utilizing jStorage for storing data in local storage. When I store the data using console.log() and later retrieve it using $.jStorage.get(), I found that the values are not being assigned to the hidden div. Can someone provide guidance o ...

Is the xmlhttprequest timeout/abort feature not functioning as anticipated?

Check out this snippet of my AJAX function: /** * This function initiates an AJAX request * * @param url The URL to call (located in the /ajax/ directory) * @param data The data to send (will be serialized with JSON) * @param callback The fu ...

I prefer to have the links activate when the mouse hovers over them, rather than when hovering over empty

Is there a way to prevent the bottom links (music, contact, archive) from being highlighted when the mouse hovers over the empty space between them and not just on the actual links themselves? I want the mouse to only react to the links it hovers over and ...

There seems to be an issue with XAMPP as I am unable to start my server due to an

A problem has occurred: Apache shut down unexpectedly. 11:58:07 [Apache] This could be caused by a blocked port, missing dependencies, 11:58:07 [Apache] insufficient privileges, a system crash, or another shutdown method. 11:58:07 [Apache] Click on ...

Toggle the active class on the parent element when it is clicked

I'm encountering a problem with my JavaScript - attempting to make this function properly. Firstly, here is the desired functionality: 1.) Add or remove the 'active' class from the parent element when clicked 2.) When clicking inside the ...

Ways to prevent modal from flickering during event changes

I'm struggling with a current issue and need help identifying the cause and finding a solution. The problem arises from having a nested array of Questions, where I display a Modal onClick to show Sub questions. However, when clicking on the Sub Quest ...

The text within the button disappears when in the :before state

After implementing the code from this codepen, I decided to use the 3rd button design. .btn { line-height: 50px; height: 50px; text-align: center; width: 250px; cursor: pointer; } .btn-three { color: #FFF; transitio ...

Anguar server encountered a startup issue and failed to initialize

My server.js file looks like this: var express = require('express'), api = require('./api'), app = express(); app .use(express.static('./public')) .use('./api', api) .get('*', ...

Adjusting diagram size based on screen width using Bootstrap and jQuery

I recently created a diagram that adjusts its size according to the screen width. However, when I implemented this code on my page, I encountered an issue where the final circle or glyph would drop to the next line instead of staying on the same line as in ...

What's causing the error "is not a function" to appear?

I am currently facing an issue while attempting to develop an angular service. Here is the code snippet for the service: var app = angular.module('plunker', []); // Filter Service that returns records with crdamt positive: app.factory('Fil ...

Positioning Google Chart in HTML

I'm attempting to arrange three distinct Google pie charts in a horizontal layout. At present, I have applied inline CSS for formatting purposes. Oddly enough, the third chart always ends up on a separate line. Could anyone kindly point out my error? ...

Using VueJS: accessing this.$store within component data property

I am interested in utilizing the data from my Vuex store in both my app and template. My Vuex store: var Vue = require('vue'); var Vuex = require('vuex'); Vue.use(Vuex) let store = new Vuex.Store({ state: { user: ...

Implement a JavaScript confirm dialog for a mailto hyperlink

Is there a way in javascript to automatically detect mailto links on the page and prompt a confirmation dialog when clicked by a user? I came across a method on this website for displaying an alert message. My knowledge of javascript is very basic. It&ap ...