输入类型=文本字段中AngularJs中的INR货币格式

时间:2016-10-19 12:17:50

标签: html angularjs

如何在文本框中以INR格式显示数字(输入类型=文本)。 因此,当用户不断更改文本时,它应相应地格式化为INR格式。

如果我们绑定ng-model,下面的代码就可以工作。



var app = angular.module('app', []);

app.controller('indexCtrl', function ($scope) {
    $scope.amount = 12564252.33;
});

app.filter('INR', function () {        
    return function (input) {
        if (! isNaN(input)) {
        
            var result = input.toString().split('.');

            var lastThree = result[0].substring(result[0].length - 3);
            var otherNumbers = result[0].substring(0, result[0].length - 3);
            if (otherNumbers != '')
                lastThree = ',' + lastThree;
            var output = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree;
            
            if (result.length > 1) {
                output += "." + result[1];
            }            

            return output;
        }
    }
});

<!DOCTYPE html>
<html ng-app="app">
<head>    
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="indexCtrl">
    Input: <input type="text" ng-model="amount">
    <h3>{{amount | INR}}</h3>
</body>
</html>
&#13;
&#13;
&#13;

基本上我希望输入字段本身应该在用户输入后立即以逗号分隔。

2 个答案:

答案 0 :(得分:0)

试试这个:

&#13;
&#13;
var app = angular.module('app', []);

app.controller('indexCtrl', function ($scope) {
    $scope.amount = 12564252.33;
});

app.filter('INR', function () {        
    return function (input) {
        if (! isNaN(input)) {
        
            var result = input.toString().split('.');

            var lastThree = result[0].substring(result[0].length - 3);
            var otherNumbers = result[0].substring(0, result[0].length - 3);
            if (otherNumbers != '')
                lastThree = ',' + lastThree;
            var output = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree;
            
            if (result.length > 1) {
                output += "." + result[1];
            }            

            return output;
        }
    }
});
&#13;
<!DOCTYPE html>
<html ng-app="app">
<head>    
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="indexCtrl">
    Input: <input type="text" ng-model="amount">
    <h3>{{ amount | currency : "RS : " }}</h3>
  OR
   <h3>{{ amount | currency : "₹ : " }}</h3>
 

</body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

看起来你想要输入框上的自定义格式。

您可以通过正则表达式和ng-pattern实现这一点。这就是你想要的吗?