So, I have to make an input for currency that stores the value as an integer in cents. I have a directive that almost works, but not quite. The following directive successfully converts the data from the model to the view and after being changed, it successfully strips everything extraneous from what's going back to the model. The problem is that it does not update the view again when the model changes. So, if the input is showing $10.00 and I type in $10.00a, the model will correctly show 1000, but the a remains in the input field.
return {
require: 'ngModel',
link: function (elem, $scope, attrs, ngModel) {
ngModel.$formatters.push(function (val) {
return '$' + (val / 100).toFixed(2);
});
ngModel.$parsers.push(function (val) {
var replaced = val.replace(/[^\d\.]/g, '');
var split = replaced.split('.');
var merged = split[0] + split[1].slice(0, 2)
return Number(merged);
});
}
}