gpt4 book ai didi

javascript - Angular 输入百分比和货币掩码

转载 作者:行者123 更新时间:2023-12-02 16:06:34 24 4
gpt4 key购买 nike

我正在使用 Angular,我很努力地寻找,但我找不到好的输入掩码。我将有两种输入,我想要的是,当我输入数字时,在货币输入中我需要一个指令或其他东西,当我输入数字时,符号“$”出现在输入的开头。

当输入是百分比时,符号“%”是指令或在字符串末尾附加“%”的东西。

enter image description here

我有这个指令只允许数字,你可以说出整数部分和小数部分的长度。如果能复用加个$或者%就完美了。

app.directive('isNumber', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, modelCtrl) {
scope.$watch(attrs.ngModel, function (newValue, oldValue) {
var decimalLenght = parseInt(attrs.decimalpart) + 1;
var integerLenght = parseInt(attrs.integerpart) + 1;
var arr = String(newValue).split("");
if (arr.length === 0) return;
if (arr.length === 1 && arr[0] === '.') return;
if (arr.length === 2 && newValue === '-.') return;
if (isNaN(newValue) || ((index_dot = String(newValue).indexOf('.')) != -1
&& String(newValue).length - index_dot > decimalLenght
) || (index_dot == -1 && arr.length === integerLenght)) {
var scopeVar = scope;
var a = attrs.ngModel.split(".");
for (i = 0; i < a.length - 1; i++) {
if (scopeVar === undefined || scopeVar == null || newValue == null) {
return;
}
scopeVar = scopeVar[a[i]];
}
scopeVar[a[a.length - 1]] = oldValue;
}
});
}
};
});

要使用它,只需输入 is-number、小数部分和整数部分

<input name="ZCHGSRP" type="text" ng-model="selectedItem.ZCHGSRP" is-number decimalpart="-1" integerpart="3" class="form-control" class="form-control" required />

最佳答案

你可以使用这个,必须对其进行微调。这只是一个粗略的方法。看看这个 fiddle https://jsfiddle.net/devjit/bgr4zvkn/1/ .

app.directive('isNumber', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, modelCtrl) {
debugger;
scope.$watch(attrs.ngModel, function (newValue, oldValue) {
var decimalLenght = parseInt(attrs.decimalpart) + 1;
var integerLenght = parseInt(attrs.integerpart) + 1;
newValue = newValue.replace('$','');
var arr = String(newValue).split("");
if (arr.length === 0) return;
if (arr.length === 1 && arr[0] === '.') return;
if (arr.length === 2 && newValue === '-.') return;
if (isNaN(newValue) || ((index_dot = String(newValue).indexOf('.')) != -1
&& String(newValue).length - index_dot > decimalLenght
) || (index_dot == -1 && arr.length === integerLenght)) {
var scopeVar = scope;
var a = attrs.ngModel.split(".");
for (i = 0; i < a.length - 1; i++) {
if (scopeVar === undefined || scopeVar == null || newValue == null) {
return;
}
scopeVar = scopeVar[a[i]];
}
scopeVar[a[a.length - 1]] = oldValue;
return;
}

var scopeVariable = scope;
var ngMod = attrs.ngModel.split(".");
for (i = 0; i < ngMod.length - 1; i++) {
if (scopeVariable === undefined || scopeVariable == null || newValue == null) {
return;
}
scopeVariable = scopeVariable[ngMod[i]];
}
scopeVariable[ngMod[ngMod.length - 1]]='$'+ newValue;
});
}
};
});

关于javascript - Angular 输入百分比和货币掩码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30669590/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com