Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS ng-bind needs to show variable + "string"

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).

like image 948
Jeffrey Roosendaal Avatar asked Oct 03 '14 12:10

Jeffrey Roosendaal


1 Answers

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).

like image 169
PSL Avatar answered Nov 14 '22 09:11

PSL