【发布时间】:2017-09-21 22:21:46
【问题描述】:
我正在尝试输入千位与“。”分开的货币。和小数用“,”分开,例如:1.000,00。这就是它应该在输入字段中显示的方式,但模型应该像 1000.00。如果我们有模型值,它应该显示为 1.000,00,如果没有,它可以保持为空到目前为止我有这样的东西:
// Code goes here
var app = angular.module("myApp", []);
app.controller("myController", function ($scope) {
$scope.amount = 12548.12
});
app.directive('smartFloat', function () {
return {
controller($scope) {
},
require: 'ngModel',
restrict: 'A',
link: function (scope, element, attr, ngModel) {
function inputValue() {
var inputVal = element.val();
var res;
//clearing left side zeros
while (inputVal.charAt(0) == '0') {
inputVal = inputVal.substr(1);
}
inputVal = inputVal.replace(/[^\d.\',']/g, '');
var point = inputVal.indexOf(",");
if (point >= 0) {
inputVal = inputVal.slice(0, point + 3);
}
var decimalSplit = inputVal.split(",");
var intPart = decimalSplit[0];
var decPart = decimalSplit[1];
intPart = intPart.replace(/[^\d]/g, '');
if (intPart.length > 3) {
var intDiv = Math.floor(intPart.length / 3);
while (intDiv > 0) {
var lastComma = intPart.indexOf(".");
if (lastComma < 0) {
lastComma = intPart.length;
}
if (lastComma - 3 > 0) {
intPart = intPart.slice(0, lastComma - 3) + "." + intPart.slice(lastComma - 3);
}
intDiv--;
}
}
if (decPart === undefined) {
decPart = "";
}
else {
decPart = "," + decPart;
}
if (intPart == "" && decPart != "") {
intPart = 0;
}
if (intPart == "" && decPart == "") {
res = null;
} else {
res = intPart + decPart;
}
if (res != inputValue) {
ngModel.$setViewValue(res);
ngModel.$render();
}
return res
}
//from model to view
ngModel.$parsers.push(inputValue);
ngModel.$formatters.push(function(val){
return val
});
}
};
})
<!DOCTYPE html>
<html>
<head>
<script data-require="angularjs@1.6.1" data-semver="1.6.1" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-app="myApp">
<div ng-controller="myController">
<input type="text" class="form-control" id="inputAmount" name="inputAmount" placeholder="Amount" ng-model="amount" smart-float />
<span class="help-block" ng-show="myForm.inputAmount.$error.float">
Invalid Amount!
</span>
{{amount}}
</div>
</div>
</body>
</html>
【问题讨论】:
-
所以你想直接交换十进制和逗号值?为什么不简单地使用像
10,000.00这样的值呢?考虑到这是直接交换,您可能需要使用第三个值作为中介。您的脚本当前返回什么,具体您遇到了哪些问题? -
在某些国家/地区,货币的格式为 1.000,00。脚本当前返回输入字段中的内容。问题是我需要在模型上以 1000.00 方式和输入 1.000,00 格式化。输入字段只允许数字和逗号输入
标签: javascript angularjs input format