用户在角度js的输入框中输入输入后如何格式化数字

时间:2015-07-03 07:21:55

标签: angularjs

任何人都可以告诉用户在角度js的输入框中输入输入后如何格式化数字。如果用户输入123456,我有文本框

我需要像这样格式化 123456

由于

2 个答案:

答案 0 :(得分:0)

使用以下filter来实现此目的:

{{ number_expression | number:fractionSize}}

下面:

number: Number to format.
fractionSize: Number of decimal places to round the number to. If this is 
not provided then the fraction size is computed from the current locale's number

格式化模式。对于默认语言环境,它将为3。

Refer Angular Docs for the same

请参阅以下Plunker:http://plnkr.co/edit/EDAMlk7Qk3urMG0JEsSI?p=preview

答案 1 :(得分:0)

您可以使用这样的指令:

define(['angular'], function () {
    angular.module("scDecimals", [])
        .directive('decimals', ['$filter', function ($filter) {
            return {
                require: 'ngModel',
                link: function (scope, element, attrs, ctrl) {
                    ctrl.$formatters.push(function (data) {
                        //convert data from model format to view format
                        var decimalPlaces = 1;
                        if (attrs["decimalplaces"]) {
                            var decPlaces = parseInt(attrs["decimalplaces"]);
                            if (!isNaN(decPlaces)) {
                                decimalPlaces = attrs["decimalplaces"];
                            }
                        }
                        var result = $filter('number')(data, decimalPlaces); //converted
                        return result;
                    });

                ctrl.$parsers.push(function (data) {
                    //convert data from view format to model format
                    var result = parseFloat(data);
                    return result; //converted
                });
            }
        }
    }]);
});

使用此功能可以将视图中的数据转换为模型,反之亦然。如果用户输入40并且您希望将其显示为40.0,则特别有用。实现这一目标的方法是使用angularjs中的$ formatters和$ parsers功能 - 在文档here中阅读更多内容。

用法示例:

<input type="text" data-decimals decimalplaces="2" ng-model="variable.value" />