作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 Angular,我很努力地寻找,但我找不到好的输入掩码。我将有两种输入,我想要的是,当我输入数字时,在货币输入中我需要一个指令或其他东西,当我输入数字时,符号“$”出现在输入的开头。
当输入是百分比时,符号“%”是指令或在字符串末尾附加“%”的东西。
我有这个指令只允许数字,你可以说出整数部分和小数部分的长度。如果能复用加个$或者%就完美了。
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/
我是一名优秀的程序员,十分优秀!