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

后端 未结 4 2108
心在旅途
心在旅途 2020-12-14 20:56

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:



        
4条回答
  •  甜味超标
    2020-12-14 21:36

    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

提交回复
热议问题