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.
The fiddle doesn’t work with current Angular version since quite a few APIs have changed since.
angular.formatteris no longer available and neither isangular.filter.The way to write it now is to use a directive and make use of
$parserand$formatteravailable on the directive controller. So your link function will look something likeAlso the filters are now accessed through
$filterservice. You can find the documentation here: https://docs.angularjs.org/api/ng/filter/numberUpdated 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