Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a percent formatted input work on latest AngularJS?

Tags:

angularjs

I saw this solution http://jsfiddle.net/gronky/GnTDJ/ and it works. That is, when you input 25, it is pushed back to model as 0.25

HTML:

<script type="text/javascript" ng:autobind
        src="http://code.angularjs.org/0.9.17/angular-0.9.17.js"></script>
<script>
function Main() {
    this.var = '1.0000';
}
</script>
<div ng:controller="Main">
    <input type="text" name="var" ng:format="percent">
    <pre>var = {{var|json}}</pre>
</div>​

JavaScript:

angular.formatter('percent', {
  parse: function(value) {
    var m = value.match(/^(\d+)\/(\d+)/);
    if (m != null)
      return angular.filter.number(parseInt(m[1])/parseInt(m[2]), 2);
    return angular.filter.number(parseFloat(value)/100, 2);
  },
  format: function(value) {
    return angular.filter.number(parseFloat(value)*100, 0);
  },
});
​

I tried making it work on latest AngularJS, it doesn't work anymore though http://jsfiddle.net/TrJcB/ That is, when you input 25, it is pushed back as 25 also, it doesn't push the correct 0.25 value to model.

Or perhaps there's already a built-in formatter for percent? I wanted currency formatter too, or comma separated number.

like image 275
Hao Avatar asked Dec 02 '12 10:12

Hao


2 Answers

Another way to implement percentage filter (works with angular#~1.2):

angular.module('moduleName')
.filter('percentage', ['$filter', function($filter) {
    return function(input, decimals) {
        return $filter('number')(input*100, decimals)+'%';
    };
}]);

How to use it:

<span>{{someNumber | percentage:2}}</span>
like image 111
Igor Rafael Avatar answered Sep 30 '22 09:09

Igor Rafael


The fiddle doesn't work with current Angular version since quite a few APIs have changed since. angular.formatter is no longer available and neither is angular.filter.

The way to write it now is to use a directive and make use of $parser and $formatter available on the directive controller. So your link function will look something like

link: function(scope, ele, attr, ctrl){
        ctrl.$parsers.unshift(
            function(viewValue){
                return $filter('number')(parseFloat(viewValue)/100, 2);
            }
        );
        ctrl.$formatters.unshift(
            function(modelValue){
                return $filter('number')(parseFloat(modelValue)*100, 2);
            }
        );
      }

Also the filters are now accessed through $filter service. You can find the documentation here: https://docs.angularjs.org/api/ng/filter/number

Updated fiddle for the original example: http://jsfiddle.net/abhaga/DdeCZ/18/

Currency filter is already available in angular: https://docs.angularjs.org/api/ng/filter/currency

like image 27
abhaga Avatar answered Sep 30 '22 10:09

abhaga