Search code examples
javascriptcssjsonangularjsdata-binding

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 }"

Solution

  • 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>