Using ngStyle in AngularJS to dynamically adjust styling based on variable values

I am looking to create a progress bar using the uikit framework. The documentation states that it can be done like this:

<div class="uk-progress">
    <div class="uk-progress-bar" style="width: 40%;">40%</div>
</div>

However, this method is static. To make it dynamic, I have written a function in Angular that calculates the percentage:

getPercentage: function() {
                var self = this;
                var done = this.downloadStatus.done.replace(/,/g, "");
                var total = this.downloadStatus.total.replace(/,/g, "");
                self.percentage = 0;
                if (parseInt(total) != 0) {
                    self.percentage = (parseInt(done) / parseInt(total)) * 100;
                }
                return self.percentage;
            } 

The width of the progress bar is determined by the "style" attribute in the HTML. Is it possible to make this width dynamic using ng-style in Angular? I attempted the following:

<div class="uk-progress">
        <div class="uk-progress-bar" ng-style="{{getPercentage()}}">40%</div>
    </div>

However, this approach was unsuccessful. Any help would be appreciated. Thank you.

Answer №1

<div class="progress-bar" ng-style="calculateProgress()">60%</div>

The ngStyle directive is designed to be dynamic, with its attribute accepting an expression (enclosed in single quotes to treat it as a static string). If no expression is provided, the style attribute will be used instead.

Answer №2

ngStyle no longer requires the use of {{}}.

Feel free to give it a shot:

angular.module('app', [])
  .controller('testController', function($scope) {
    $scope.test={color: "red"}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>


<div ng-app="app">
  <div ng-controller="testController">
    
    <div ng-style="test">{{test}}</div>        
    <input type="text" ng-model="test.color"/>
    
  </div>
</div>

Answer №3

Consider storing the dynamic style in the scope variable

$scope.progressBarWidth = getPercentage();

and continually update it when the download progress or any other event triggers the progress bar to move, within an $asyncEval

$scope.$evalAsync(function() {
   $scope.progressBarWidth = getPercentage();
});

By doing this, you ensure that the progress bar stays up to date. Your HTML should be like this:

<div class="uk-progress-bar" ng-style="progressBarWidth">40%</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

Primeng - Concealed dropdown values within a scrollable table header

Recently, I integrated Primeng p-table with a filter and frozen column feature (with one column being fixed while the others are movable). However, I encountered an issue with the select dropdown in the header. When I try to open the dropdown, the values a ...

Angular routing based on login status

Currently, I am utilizing active directory windows authentication to verify if a user is logged in. The client-side code is written in Angular while the server-side code is in C#. How can I implement Angular to verify user authorization for accessing a pa ...

Using AngularJS 1 and HTML, creating a modal within a modal or a hidden div that can be shown and hidden in a modal

I already have a modal set up that allows me to add information about "thing1", but I also need to include specific details related to that "thing1" within the same modal. These additional details should appear in the modal when I click on "add more spec ...

Align the single element to the right

Is there a way to right align a single element within a dropdown list using Bootstrap 5? I typically use "justify-content-end" for this purpose, but it doesn't seem to work in this case. <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn- ...

Ways to Influence Nearby Element using CSS Hover Effects

Below is the HTML code snippet: <div id="flexi-overlay"> <a id="flexi-overlay-image-link-container" href="#" class="popup image-link"?> <img src="image.jpg" /> </a> <span id="flexi ...

Efficiently running multiple PHP pages with just one simple click

Below is the code fragment that I currently have: <html> <script type="text/javascript"> function Run() {var a=["ONE" ,"TWO" ,"THREE", "FOUR", "FIVE"]; window.location.href = "index.php?w1=" +a;} </script> <body> <input type="b ...

The compare function in bcryptjs will result in a false output if the passwords include numerical

I have successfully used bcryptjs to hash my passwords during user registration. However, I am facing an issue with the bcrypt.compare function when attempting to log in. The function returns a false promise when passwords contain numbers or special charac ...

implement adding a division element to the DOM using the append

I am facing an issue with this particular code. The intended functionality is to create multiple divs in a loop, but it seems to be dysfunctional at the moment. Upon clicking, only one div appears and subsequent clicks don't trigger any response. < ...

What is the best way to update all React components with a context without using a provider?

Considering this straightforward custom hook import React, { createContext, useContext } from 'react'; const context = { __prefs: JSON.parse(localStorage.getItem('localPreferences') || null) || {} , get(key, defaultValue = null) ...

Issues with implementing Bootstrap 4 navbar on a Rails 5 application

I'm currently in the process of transitioning my static HTML/CSS/JS website to a Rails application. Using Bootstrap 4, I had all the functionality and CSS classes working perfectly on the static site. However, after the migration to the Ruby app, the ...

Position the button to display aligned to the right below the paragraph

I have a text paragraph along with a button that I am trying to align properly on the page. Despite my efforts, I am having trouble getting the button to display right-aligned below the text as desired. Here is the current layout: Is there a way to achie ...

Using Vue.js to send a slot to a child component in a nested structure

Check out this interesting modal component configuration //modal setup <template> <slot></slot> <slot name='buttons'></slot> </template> Imagine using it like a wizard //wizard setup <template> ...

Rapid polygon merging with JavaScript

I have a large geoJSON file containing polygons and multi-polygons, totaling 2.5 MB in size. My goal is to merge all these shapes to display them on a map within a web browser environment. In my Python workflow, I am using shapely.ops.unary_union which p ...

"Troubleshooting the issue of addEventListener failing to work in conjunction

window.addEventListener("onbeforeunload",function() {return "are you sure?"}); Unfortunately, the above code doesn't seem to be functioning as intended. The confirmation box is not being displayed and the page closes without any prompts. While I am ...

What modifications can I make to my JavaScript code in order to enable clicking through an HTML list?

I'm facing an issue with getting my list to function properly. I want users to be able to navigate through the list by clicking on next and previous buttons, but for some reason, the code is not working as expected. When they click next, the next item ...

Having trouble with the repeat-item animation feature not functioning correctly

Take a look at this Plunker, where the animation for adding an item only seems to work properly after an item has been deleted from the list. Any suggestions on how to resolve this issue? Here is the CSS code: .repeat-item.ng-enter, .repeat-item.ng-leave ...

Unable to link to 'mdMenuTriggerFor' as it is not a recognized attribute of 'button'

During the execution of my angular application using ng serve, I encounter the following error: Can't bind to 'mdMenuTriggerFor' since it isn't a known property of 'button' Despite importing all the necessary components, I a ...

Modify the content of a table cell once the hyperlink in a different cell on the corresponding row is selected

I currently have a table that displays items pulled from a database. Each item has a checkbox to mark it as "Valid", which successfully updates the status in the database. However, I am looking for a way to dynamically update the text on the page after the ...

Issue with scrolling feature on chrome browser

I've noticed that this piece of code functions correctly in Firefox, but unfortunately doesn't seem to be working in Chrome. In Chrome, the scrolling feature is not functioning as expected - the click event fires, but it fails to move to the posi ...

Is there a way to send the image's name as a parameter?

I am facing a challenge in achieving a specific task and need some guidance. My current approach involves passing the image name as a parameter to the cancelimage.php script, but it seems like I am not utilizing the variable 'image_file_name' cor ...