Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting HTML element width using ng-style and percentage value in AngularJS

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 }" 
like image 481
metacubed Avatar asked Jul 25 '14 02:07

metacubed


People also ask

What is Ng style in Angular JS?

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.

What is NgClass and NgStyle?

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.


2 Answers

Another way to achieve this is

[style.width.%]="completionPercent" 

In your code

<div id="progressBackground" ... > <div id="progressBar"      ng-model="..."      [style.width.%]="completionPercent"      ... ></div> 

like image 36
Evita Dalmeida Avatar answered Sep 19 '22 13:09

Evita Dalmeida


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> 
like image 119
Andrew Avatar answered Sep 17 '22 13:09

Andrew