任何人都可以帮我编写一个输入掩码,使用angularjs格式化价格而不使用任何插件。 我想如果用户写入56,然后在价格字段中,它会在第二个数字后自动出现一个点,如果用户只输入56,那么它显示为56.00。如果有人只写一个数字3(比如说),那么它应该是03.00.i需要点前2位数和点后2位数。
我试过这个,但是在写完第二个数字后它没有自动显示一个点。
angular.module('myApp.controllers', []).
controller('MyCtrl1', ['$scope',function($scope) {
$scope.phoneNumber;
$scope.show = false;
var count = 0;
$scope.update = function(){
var value = $scope.phoneNumber.toString().trim().replace(/^\+/, '');
if (value.match(/[^0-9.]/)) {
$scope.phoneNumber = 0;
$scope.show = true;
return;
}
$scope.show = false;
var pre, price, number ,post;
switch (value.length) {
case 1: // +1PPP####### -> C (PPP) ###-####
if(value == ".")
{
pre = "0";
price = 0;
number = 0;
post = 0;
}
else{
pre = 0;
price = value;
number = 0;
post = 0;
}
break;
case 2: // +CPPP####### -> CCC (PP) ###-####
if(value[0] == ".")
{
pre = "0";
price = 0;
number = value[1];
post = 0;
}
else if(value[1] == ".")
{
pre = 0;
price = value[0];
number = 0;
post = 0;
}
else
{
pre = value[0];
price = value[1];
number = 0;
post = 0;
}
break;
case 3: // +CCCPP####### -> CCC (PP) ###-####
if(value[0] == ".")
{
pre = "0";
price = 0;
number = value[1];
post = value[2];
}
else if(value[1] == ".")
{
pre = 0;
price = value[0];
number = value[2];
post = 0;
}
else if(value[2] == ".")
{
pre = value[0];
price = value[1];
number = 0;
post = 0;
}
else
{
pre = value[0];
price = value[1];
number = value[2];
post = 0;
}
break;
case 4:
if(value[0] == ".")
{
pre = "0";
price = 0;
number = value[2];
post = value[3];
}
else if(value[1] == ".")
{
pre = 0;
price = value[0];
number = value[2];
post = value[3];
}
else if(value[2] == ".")
{
pre = value[0];
price = value[1];
number = 0;
post = value[3];
}
else
{
pre = value[0];
price = value[1];
number = value[2];
post = value[3];
}
break;
default:
pre = value[0];
price = value[1];
number = value[2];
post = value[3];
}
$scope.phoneNumber = (pre + price +"." + number + post).trim();
};
}])
答案 0 :(得分:0)
你的意思是这样吗?
<div ng-app="myApp">
<input type="number" ng-model="price"/>
Price: {{price | customNumber}}
</div>
app = angular.module('myApp', []);
app.filter('customNumber', function($filter) {
return function(input) {
input = $filter('number')(input % 100, 2);
return (input < 10) ? '0' + input : input;
};
});