-2
我想输入货币,其中千与“。”分开。和小数分隔“,”例如:1.000,00。这就是它应该如何显示在输入字段,但模型应该是1000.00。如果我们有借鉴价值,应该显示为1.000,00,如果有没有可能留空到目前为止,我有这样的事情:AngularJS的货币输入
// 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="[email protected]" 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格式的模型。并且输入字段只允许数字和逗号输入 – Ivan