Modify the width of the progress bar in Bootstrap using AngularJS

I'm new to AngularJS and I'm attempting to dynamically update the width of a progress bar based on changes in my controller.

Here is what I currently have:

<span id="percentage">$ {{getTotal()}} ({{getPercentage()}}%)</span>
<div class="progress-bar progress-bar-warning" 
  role="progressbar" aria-valuenow="10" aria-valuemin="0" 
  aria-valuemax="100" style="width: 10%">
    <span class="sr-only">10% Complete (warning)</span>
</div>

In my controller, I have the following:

$scope.total = 254.78;
$scope.threshold = 15000;

$scope.getPercentage = function () {
    return (($scope.total * 100) / $scope.threshold).toFixed(2);
}
$scope.getTotal = function () {
    return $scope.total;
}

How can I update the value of the progress bar's width property?

Thank you, Alberto.

Answer №1

To achieve this, utilize the ng-style directive.

<span id="percentage">$ {{getTotal()}} ({{getPercentage()}}%)</span>
<div class="progress-bar progress-bar-warning" 
  role="progressbar" aria-valuenow="{{getPercentage()}}" aria-valuemin="0" 
  aria-valuemax="100" ng-style="{width : ( getPercentage() + '%' ) }">
    <span class="sr-only">{{getPercentage()}}% Complete (warning)</span>
</div>

Answer №2

A great solution for this would be to create a custom directive that handles the width calculation internally.

module.directive("progressbar", function () {
    return {
        restrict: "A",
        scope: {
            total: "=",
            current: "="
        },
        link: function (scope, element) {

            scope.$watch("current", function (value) {
                element.css("width", scope.current / scope.total * 100 + "%");
            });
            scope.$watch("total", function (value) {
                element.css("width", scope.current / scope.total * 100 + "%");
            })
        }
    };
});

http://jsfiddle.net/rGWUR/10/

Answer №3

Here's an example of how you can achieve this:

<div class="progress-bar progress-bar-success"
  role="progressbar" aria-valuenow="{{calculatePercentage()}}" aria-valuemin="0" 
  aria-valuemax="100" style="width: {{calculatePercentage()}}%">
    <span class="sr-only">{{calculatePercentage()}}% Complete (success)</span>
</div>

Answer №4

Personally, I believe that utilizing the Angle-UI progress bar is a more efficient solution rather than attempting to create something new from scratch. You can find more information about Angle-UI progress bars here.

<uib-progressbar value="50"></uib-progressbar>

Answer №5

You have the ability to create a personalized ng-style:

 <div class="progress-bar progress-bar-warning"
    role="progressbar" 
    aria-valuenow="10"
    aria-valuemin="0"
    aria-valuemax="100" 
    ng-style="customStyle">
        <span class="sr-only">10% Complete (warning)</span>
 </div>

and within the controller:

 $scope.customStyle = {
   width : $scope.calculateProgress() + '%'     
 };

Check out the Demo

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

The function .save() in Mongoose is limited to executing only five times

While working with my House data seeder, I encountered a strange issue. Even though my code loops through the end, it only saves 5 records in the month model. const insertMonths = houses.map((house, i) => { const months = new Month({ year: &qu ...

utilizing an ajax request to clear the contents of the div

When I click on Link1 Button, I want to use ajax to empty the contents in the products_list div <button type="w3-button">Link1</button> I need help with creating an ajax call that will clear the products in the product_list when the link1 but ...

What is the best way to iterate through my array and display each value within my button element?

I have a challenge where I'm trying to iterate over an array named topics. This array contains the names of various people. Within my loop, my goal is to extract each name and insert it into a button as text. When I use console.log within my loop, I ...

Selective Circle Appending Techniques

I am having some issues with my bubble chart code. The data file I am working with contains instances where the GDPperCapita and/or LifeExpectancy values are either 0 or NaN, causing problems when appending circles to the chart. I would like to know if th ...

Mediawiki functionality experiencing issues within iframe display

Currently, I am working with MediaWiki built in PHP. Due to certain reasons, I have to embed this application within an iframe. All functionalities are running smoothly except for the Edit link for pages. The issue arises when I try to access the second li ...

ES6 promises: the art of connecting functions with parameters

Looking for a way to chain functions with delays? Here is an example of what I have tried: Promise.resolve() .then(setKeyframe('keyframe-0')) .then(delay(3000)) .then(setKeyframe('keyframe-1')) .then(delay(3000)) .then(setKeyframe(&apo ...

Iterating through a nested array of objects to merge and accumulate values

Just started learning Javascript. I've been trying to wrap my head around it for hours, looking at examples, but still struggling. I'm working with an array of objects that have nested properties which I need to loop through and consolidate. ...

Angular-ui-bootstrap-tabs feature smooth transitions when switching between tabs, but lacks animation when moving

Just made some updates to an example by user @austin Encountering an issue when trying to transition backwards (from tab3 to tab2), but it works fine when transitioning forward. I'm not sure what I'm missing here, so any help would be appreciate ...

Manipulate Input Classes by Adding and Removing Them

I am currently using masked JS in some input fields, specifically for telephone numbers. However, I am facing an issue where phone numbers can vary in length, either 10 or 11 digits. I need to switch the class based on whether a checkbox is checked. Here i ...

Transfer responsibilities of events to the canvas and then fetch the Element in the handler

Currently, I am utilizing the Raphaël library to create a network graph, where nodes are depicted as circles. Users have the ability to dynamically add nodes by clicking on the canvas. When a new node is added, an Element object is pushed into both a Set ...

Updating tooltip text for checkbox dynamically in Angular 6

Can anyone help me with this code? I am trying to display different text in a tooltip based on whether a checkbox is active or not. For example, I want it to show "active" when the checkbox is active and "disactive" when it's inactive. Any suggestions ...

Create a dynamic and interactive website using a combination of jQuery and AngularJS

I recently came across an interesting tidbit on the FAQs of Angular stating that "Angular can use jQuery if it's present in your app when the application is being bootstrapped". This got me thinking, is it considered a best practice to include both j ...

Issue encountered in Next.JS when attempting to validate for the presence of 'window == undefined': Hydration process failed due to inconsistencies between the initial UI and the server-rendered

I encountered an issue that says: Hydration failed because the initial UI does not match what was rendered on the server. My code involves getServerSideProps and includes a check within the page to determine if it is running in the browser (window==&apo ...

How to control the activation of ng-click in an Angular application

Modify the condition in ng-click so that it is clickable only if the length is greater than 1. ng-click="filtered.length > 1 ? 'false' : 'true' || showSomething($index)" What needs to be corrected here? ...

Ensuring the validity of input tags

I encountered an issue with an input tag that has a specific logic: https://codepen.io/ion-ciorba/pen/MWVWpmR In this case, I have a minimum value retrieved from the database (400), and while the logic is sound, the user experience with the component lea ...

Align watermark content to the far left side

Having trouble getting my watermark to align properly on the left side of my website's main content. Here is how it currently looks: The issue arises when I resize the screen or switch to mobile view, as the watermark ends up covering the main conten ...

Purging data when no input is detected in React.js

I need to figure out a reliable way to detect when my input field has been cleared so that I can clear the associated data. Currently, I am using the logic if (searchTerm.length === 0) to check for a cleared input. However, I have also experimented with i ...

What's the alternative now that Observable `of` is no longer supported?

I have a situation where I possess an access token, and if it is present, then I will return it as an observable of type string: if (this.accessToken){ return of(this.accessToken); } However, I recently realized that the of method has been deprecated w ...

Close the Bootstrap modal once the redirect is selected

After clicking the "Select" button, I want to close my modalbox and return to the same page. Currently, I am on shuffle.php and I open the modalbox by calling the code in updaterecords.php. However, when I click "Select," I am redirected to updaterecords. ...

Chrome's CSS columns cannot contain iframes without causing them to escape their

I'm currently attempting to incorporate Iframes within a 3-column grid. HTML <div id="blogPosts"> <div class="blogPost"> <iframe width="100%" src="https://www.youtube.com/embed/YqeW9_5kURI" frameborder="0" allowfullscre ...