I'm looking for a way to format an input
element to format for currency. Specifically I want the commas in there for thousands.
The initial solution was to just format the value in the controller and return that to the view. But then to do my calculations I have to strip all of that out again. Then I came across $formatters
and $parsers
for ngModelController
. Essentially it allows you to create pipeline functions. The first formats the value for the user. The second parses the value to be used in the controller. Precisely what I want.
My solution only works on page load though. Check out my fiddle.
myApp.directive('thousandsformatter', function ($filter) {
return {
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
ctrl.$formatters.push(function (data) {
var formatted = $filter('currency')(data);
console.log(formatted);
//convert data from model format to view format
return formatted; //converted
});
ctrl.$parsers.push(function (data) {
console.log(data);
//convert data from view format to model format
return data; //converted
});
}
};
});
How can I get this to update as the user types?