I am currently working on developing a custom directive for creating personalized masks for input fields. While there are other libraries available, I often need to create specific input formats tailored to the company's requirements (e.g., "OS.012-08765"), so I prefer to build my own directive.
So far, I have successfully formatted the number according to the specified pattern, but only in the model and not in the actual input field. For this demonstration, I will be using a money input because it is easier to work with (in my opinion). Here is the code I am utilizing:
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;
}
}
}
}
Here is the Plunker link with the provided code: http://plnkr.co/edit/UjZkPFL0V4FRrDUL9jAJ?p=preview
The main issue arises when typing in the input field as the value lacks the desired mask and displays only numbers. However, the model retains the correct formatting.
Based on this problem, I am facing two main challenges:
- Firstly, I aim to switch these outcomes where entering text in the textbox exhibits the mask while the model remains plain numbers without any masking.
- Secondly, even when creating an update button to modify the model value, it does not adhere to the set mask and displays the plain text instead.
How can these issues be effectively resolved?