NickJ
NickJ

Reputation: 9559

Angular JS number filter

I had the following expression in Angular:

<br/><i>{{getFieldValue(teamMember.reportingData.fields, fieldname, 'meanValue' | number:2)}}</i>

where getFieldValue is a function on my controller. This was working as expected, and truncating the numeric result to 2 decimal places.

However, sometimes getFieldValue returns a string result. When that happens, it is not displayed at all. This is probably because truncating a string to 2 decimal places does not make sense.

To get round this, I tried to move the filter inside getFieldValue and only apply it to numeric results. To do this, I need a way of specifying a filter in Javascript, not as an expression in HTML. According to the docs this is possible, but the explanation is hard to follow.

Here is my attempt:

HTML:

<br/><i>{{getFieldValue(teamMember.reportingData.fields, fieldname, 'meanValue')}}</i>

part of getFieldValue :

if (field.numeric) {
   fieldValue = $filter('number')([], field[aggregate], 2);
 } else {
   fieldValue = field[aggregate];
 }   

This does not work, I get what seems to be an empty string back. How to I do this properly?

Upvotes: 0

Views: 591

Answers (2)

addon kishor
addon kishor

Reputation: 43

   var isnum = angular.isNumber(field[aggregate]);

    if(isnum){   
        fieldValue = $filter('number')(field[aggregate], 2) 
    }else{   
        fieldValue = field[aggregate]; 
     }

number filter in angularjs

Upvotes: 1

Mudasser Ajaz
Mudasser Ajaz

Reputation: 6257

Use like this

 fieldValue = $filter('number')(field[aggregate], 2);

See Documentation of number filter.

Upvotes: 2

Related Questions