Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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 }"
share|improve this question
    
So can't you just add the percentage in the object to begin with? {"completionPercent": "42%"} –  epascarello Jul 25 at 2:42
    
@epascarello The JSON comes from another service. I could pre-process it in the controller and add in a new String property, but I'd leave that as a last resort. –  metacubed Jul 25 at 2:45

1 Answer 1

up vote 6 down vote accepted

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>
share|improve this answer
2  
Here's a fiddle... jsfiddle.net/L5C5Y –  Anthony Chu Jul 25 at 2:44
    
Good grief.. is it really that easy? I've been trying everything but the obvious for hours! –  metacubed Jul 25 at 2:47
    
It works! Thank you! –  metacubed Jul 25 at 2:53
    
If you find yourself fighting Angular, take a step back and really try to think about what you are trying to achieve. There are so many ways to do things in angular it's really about choosing what best suits the situation. The knowledge will come with time and experience. –  Andrew Jul 25 at 3:02
    
Yeah, I never realized that any javascript is allowed in there. :) –  metacubed Jul 25 at 3:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.