Reputation: 14309
I have an input form that takes currency values in the hundreds, millions, billions etc. To make it user-friendly I'd like those custom input fields to show and let the user input e.g. '1.5M' instead of 1500000, '1B' instead of 1000000000 and so on. For that purpose I created a FormatServices
service with two methods currParse(value: string): number
and currFormat(value: number): string
and they do what they are supposed to i.e. transform between model and display values and back.
Now I define a custom currency directive as follows:
.directive("currency", function($filter, formatServices: FormatServices){
// convert to number
var p = function(viewValue){
if (angular.isDefined(viewValue)) {
return $filter('number')(formatServices.currParse(viewValue));
}
};
var f = function(modelValue){
if (angular.isDefined(modelValue)) {
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< HERE WHAT FILTER TYPE?
return $filter('???')(formatServices.currFormat(modelValue));
}
};
return {
require: 'ngModel',
link: function(scope, ele, attr, ctrl){
ctrl.$parsers.unshift(p);
ctrl.$formatters.unshift(f);
}
};
})
In the annotated line I need a filter type. Looking at the available filter types in Ng I tried with number
but doesn't work because is a string output. json
filter type works but the output includes double quotes around it. uppercase
and lowercase
don't work either because they destroy my format e.g. I can have 100k or 1.5M. There is no text
filter so I don't know what to fill in there to have this working ...
Upvotes: 0
Views: 173
Reputation: 1354
You can make you own filter. This example make an IntegerCurrency.
.filter('myCurrency', ['$filter', function ($filter) {
return function(input) {
input = parseFloat(input);
if(input % 1 === 0) {
input = input.toFixed(0);
}
return '$' + input;
//you can change $ or € put ',' '.' '-' or decorate whate ever the output.
};
}])
Upvotes: 1