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

后端 未结 4 2105
心在旅途
心在旅途 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:43

    I modified abhaga's answer to allow for .## and ## input. In my opinion this is a lot more user-friendly

    link: function(scope, element, attr, ngModel) {
                ngModel.$parsers.unshift(
                    function(viewValue){
                        var perc = parseFloat(viewValue);
                        if (perc<0 || perc>100 || !isFinite(perc)){
                            return null;
                        }
                        if (perc>1 && perc<=100){
                            return parseFloat($filter('number')(perc/100));
                        }
                        return perc;
                    }
                );
                ngModel.$formatters.unshift(
                    function(modelValue){
                        if(!isFinite(modelValue)){
                            return "";
                        }
                        return $filter('number')(parseFloat(modelValue)*100, 2);
                    }
                );
            }
    

提交回复
热议问题