Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 826
  • Last Modified:

Custom filter using AngularJS

Hi Experts,

I get a numeric value from a server and would like to format as a percent and display in the UI. How can I do this in Angularjs using custom filter? Here is my requirement

Data from server                     UI  

0                                 should display as NA
0.1234                        should display as 12.34%  //2 decimals
0.05                            should display as  5.00%  //2 decimals
6.24                            should display as  6.24%  

Thanks in Advance
0
ksd123
Asked:
ksd123
2 Solutions
 
leakim971PluritechnicianCommented:
Test page : http://jsfiddle.net/ausS4/

var myApp = angular .module("myApp",[]) .controller(myCtrl) .factory("Data", function() { return { get: function() { return [0,0.1234,0.05,6.24]; } } }); var myCtrl = function($scope, Data) { $scope.numbers = []; var data = Data.get(); for(var i=0;i<data.length;i++) { $scope.numbers.push( myFormatter(data[i]) ); } } var myFormatter = function(value) { value = value * 1; if(value == 0) { return "NaN"; } else if(Math.abs(value) > 1) { return value.toFixed(2) + "%"; } return (value * 100).toFixed(2) + "%"; }
0
 
Kyle HamiltonData ScientistCommented:
this would be the angular filter way to do it:

angular.module('MyApp').
  filter('toPercent', function() {
    return function (value) {
		if (value == 0) {
		    value = "NA";
		} else if (Math.abs(value) >= 1){
		    value =  (value).toFixed(2) + "%";
                }else{
		    value =  (value *  100).toFixed(2) + "%";
                }
                return value;
    }
  })

Open in new window


then in the template, you can use your filter like this;

{{value|toPercent}}

Open in new window

0
 
ksd123Author Commented:
Thank you guys
0

Featured Post

Ask an Anonymous Question!

Don't feel intimidated by what you don't know. Ask your question anonymously. It's easy! Learn more and upgrade.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now