I have a JSON response object which contains a percentage value. For example:
{ completionPercent: 42 }
The UI result I'm aiming for is:
┌──────────────────────────────────────────────────┐ |█████████████████████ | └──────────────────────────────────────────────────┘
The JSON object is used as the ng-model
of an element in AngularJS. Now I want to bind the completionPercent
as the width of an element in AngularJS. But CSS width
expects a String like '42%'
, not a Number. So the following does not work:
<div id="progressBackground" ... > <div id="progressBar" ng-model="..." ng-style="{ 'width': completionPercent }" ... ></div> </div>
Currently, I have this working by generating the entire style in the controller:
ng-style="getStyleFromCompletionPercent()"
But this is not a good idea, as it becomes very difficult to extend the ng-style
. Is there another way to implicitly specify that the width is in percent? Something like this would be ideal:
ng-style="{ 'width-percentage': completionPercent }"
AngularJS ng-style Directive The ng-style directive specifies the style attribute for the HTML element. The value of the ng-style attribute must be an object, or an expression returning an object. The object consists of CSS properties and values, in key value pairs.
The NgClass and NgStyle directives are used to apply style to the HTML element conditionally. The NgClass allows you to apply whole class based on condition whereas NgStyle gives you more flexibility to set individual properties.
Another way to achieve this is
[style.width.%]="completionPercent"
In your code
<div id="progressBackground" ... > <div id="progressBar" ng-model="..." [style.width.%]="completionPercent" ... ></div>
The code within your ng-style attribute is a javascript object, so you could append a percentage symbol on the end of you width value. As you are appending a string to a number it will also convert the value of width to a string.
<div id="progressBackground" ... > <div id="progressBar" ng-model="..." ng-style="{ 'width': completionPercent + '%' }" ... ></div> </div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With