I'm trying to create a directive to create custom mask for my input. I know there are other libraries I could use, but sometimes I need a custom input based on the company needs, (e.g. "OS.012-08765"), so I'd rather create my own directive.
So far I was able to format the number on the pattern I need, but not on the input, only on the model. For this example I'll be using a money input, because it's simpler to work with (I think). This is the code I'm using:
function myMoney() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModelCtrl) {
ngModelCtrl.$formatters.push( formatInput );
ngModelCtrl.$render = renderViewValue;
ngModelCtrl.$parsers.push( parseOutput );
function formatInput( value ) {
value = formatNumber(value);
return value;
}
function parseOutput( value ) {
value = formatNumber(value);
return value;
}
function renderViewValue() {
element.html( ngModelCtrl.$viewValue );
}
function formatNumber(value) {
if(!value) {
value = '000';
}
var checkValue = value.replace(/[^0-9\.]/g, '');
if(checkValue != value) {
value = checkValue;
}
value = value.toString();
if(value.length < 3) {
value = ('000'+value).slice(-3);
}
var
firstChar = value.slice(0, value.length-2),
lastChar = value.slice(-2),
firstChar = Number(firstChar).toLocaleString(),
finalChar = '$'+firstChar+','+lastChar;
return finalChar;
}
}
}
}
And this is a plunkr with the code: http://plnkr.co/edit/UjZkPFL0V4FRrDUL9jAJ?p=preview
The main problem is where the output is, if you start typing on the input, the value doesn't have the mask, is just numbers. But the model has the proper mask.
So, based on this, I have 2 main issues:
- First: I want to invert these results. I want to type in the textbox and have the mask on the textbox while the model is just plain number (without the mask).
- Second: If I create a button to update the value on the model, it doesn't get formatted within the mask, it stays plain text.
How can I solve these problems?
<input placeholder="__.___-_____ ">
? So you won't have to worry about replacing "_" with your actual character. – Edmar Miyake yesterday