问题描述
我正在尝试创建一个指令来为我的输入创建自定义掩码.我知道我还可以使用其他库,但是有时我需要根据公司需求进行自定义输入(例如"OS.012-08765"),所以我宁愿创建自己的指令.
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;
}
}
}
}
这是一个带有代码的插件: http://plnkr.co/edit/UjZkPFL0V4FRrDUL9jAJ ?p =预览
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:
- 首先:我想反转这些结果.我想在文本框中键入文本,并在模型上显示蒙版,而模型只是纯数字(不带蒙版).
- 第二:如果我创建一个按钮来更新模型上的值,则它不会在蒙版内格式化,而是保持纯文本格式.
我该如何解决这些问题?
How can I solve these problems?
推荐答案
尝试使用ui掩码, https://htmlpreview.github.io/?https://github.com/angular-ui/ui-mask/master/demo/index.html ,在 Mask Definition 字段下输入 AA.999-99999 以匹配您的模式.
try to use ui mask, https://htmlpreview.github.io/?https://github.com/angular-ui/ui-mask/master/demo/index.html, enter AA.999-99999 under Mask Definition field to match your pattern.
<input type="text"
ng-model="serviceOrderNumber"
ui-mask="AA.999-99999"
ui-mask-placeholder
ui-mask-placeholder-char="_"/>
这篇关于AngularJS创建输入蒙版的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!