[英]How to set decimal mask in javascript
我正在嘗試將兩個數字的十進制掩碼設置為我的javascript應用程序。 我嘗試使用以下解決方案,因為我在目前使用的所有掩碼中都使用ui-mask:
<input id="DebitValue" type="text" placeholder="{{appResources.ContractCreateEditPaymentValuePlaceholder}}" ng-model="DebitValue" ui-mask-placeholder ui-mask="?9?9??9?9?9?9?.?9?9?" model-view-value="true" name="DebitValue" required>
但是我沒有實現我想要的,因為例如我不能插入0.99
作為值,所以我需要插入000000.99
。
我也檢查了這個解決方案 ,但是numeric
或輸入inputmask
都沒有對我的輸入執行任何操作,我只是能夠寫出我想要的東西。
您可以使用ng-pattern="/^[0-9]+(\\.[0-9]{1,2})?$/"
僅接受最多2個小數位且帶點分隔符的數字。
如果您想要更多,請使用類似以下的指令:
.directive('currencyInput', function ($browser, $filter) {
return {
require: 'ngModel',
link: function ($scope, $element, $attrs, ngModel) {
var listener = function () {
var value = $element.val().replace(/,/g, '');
$element.val($filter('number')(value, 0));
};
// This runs when we update the text field from element
ngModel.$parsers.push(function (viewValue) {
return parseInt(viewValue.replace(/,/g, ''), 10);
});
// This runs when the model gets updated on the scope directly and keeps our view in sync
ngModel.$formatters.push(function (modelValue) {
return modelValue == null || modelValue.length === 0 ? '' : $filter('number')(modelValue, 0);
});
ngModel.$viewChangeListeners = function () {
$element.val($filter('number')(ngModel.$viewValue, 0))
}
$element.bind('change', listener);
$element.bind('keypress', function (event) {
var key = event.which;
// If the keys include the CTRL, SHIFT, ALT, or META keys, or the arrow keys, do nothing.
// This lets us support copy and paste too
if (key === 0 || key === 8 || (15 < key && key < 19) || (37 <= key && key <= 40)) {
return;
}
$browser.defer(listener); // Have to do this or changes don't get picked up properly
});
$element.bind('paste cut', function () {
$browser.defer(listener);
});
}
}
})
然后在輸入元素上使用它,比如說:
<input currency-input ng-maxlength="10" ng-model="myDecimal" type="text">
如果只需要兩個小數,則應使用硬編碼數字過濾器或將其作為指令的參數接收:
$element.val($filter('number')(value, 2));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.