AngularJS ng-bind needs to show variable + "string"
Asked Answered
S

1

6

I've created an ng-bind element in my template, which displays a number rounded by one decimal. How do I add a % to the end of it, from within the ng-bind logic?

My code:

<span ng-bind="variable | number: 1" 
      class="animated" ng-show="variable" 
      ng-class="{'fadeIn':variable}"></span>

Results in (for example) 4.5 but I want it to be 4.5%.

The thing is, I want to add a %-character to the end of it, but how? I'd rather not add a second span, with the exact same logic, just for that one character, and ng-bind="variable + '%' | number: 1" is not working. I'd also like to avoid extra code in my controllers/directives, since I think this is more a template thing (and I only need to use it just a few times).

Singlehandedly answered 3/10, 2014 at 12:40 Comment(4)
You could use interpolation <span class="animated" ng-show="variable" ng-class="{'fadeIn':variable}">{{variable | number: 1}}%</span> or create/use a percentage filter... or create a custom filter which does the just of rounding number and adding percentage.. How about ng-bind="(variable | number: 1) + '%'" Pannier
The first two suggestions are a little 'overkill', since I only need this 3-4 times within my whole project. But the last thing you said was exactly what I wanted. works great. Thanks. You may file this as the answer btw, so I can mark it as such.Singlehandedly
If you do it in ng-bind or use interpolation... there is no overkill, both are almost virtually the same. using filters yes, if you dont need to do more complex stuffs on it.Pannier
True, I didn't really knew what you ment with interpolation, but now that I see the example, it just the basic way of showing variables. My bad.Singlehandedly
P
14

Issue is you are provinding invalid number to the number filter. Instead you could move addition of percentage to the end after number filter is done.

<span ng-bind="(variable | number: 1) + '%'" 
  class="animated" ng-show="variable" 
  ng-class="{'fadeIn':variable}"></span>

Or use interpolation

<span class="animated" ng-show="variable" ng-class="{'fadeIn':variable}">{{variable | number: 1}}%</span>

Demo

Or you could even create a filter that performs rounding of number and addition of % and just use that filter, or another custom filter to add a percentage (Just make sure it is not an overkill, unless you need to do it in lots of places).

Pannier answered 3/10, 2014 at 12:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.