将货币过滤器应用于angularjs中的输入字段 [英] Apply currency filter to the input field in angularjs

查看:144
本文介绍了将货币过滤器应用于angularjs中的输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用span标签时,我可以应用货币过滤器,如

Hi when I am using span tags I can apply the money filter like

<div ng-repeat="item in items">
    <span>
        {{item.cost | currency}}
    </span>
</div>

我想知道如何在输入标签中应用相同的货币过滤器。即

I am wondering how I can apply same currency filter in input tag. i.e

<div ng-repeat="item in items">
    <input type="text"  ng-model="item.cost | currency" />
</div>

当我尝试将货币过滤器应用于输入字段时,它不起作用。请让我知道如何将货币过滤器应用于输入字段。谢谢

When I try to apply currency filter to the input field as above it doesnt work. Please let me know how to apply currency filter to input field. Thanks

推荐答案

我创建了一个处理格式输入字段的简单指令。这是一个 jsfiddle 示例。要使用它,请将其添加到现有代码中。

I created a simple directive that handles formatting input fields. Here is a jsfiddle example. To use it add this to your existing code.

<div ng-repeate="item in items">
    <input type="text"  ng-model="item.cost" format="currency" />
</div>

并将此指令添加到您的代码中。

And add this directive to your code.

// allow you to format a text input field.
// <input type="text" ng-model="test" format="number" />
// <input type="text" ng-model="test" format="currency" />
.directive('format', ['$filter', function ($filter) {
    return {
        require: '?ngModel',
        link: function (scope, elem, attrs, ctrl) {
            if (!ctrl) return;

            ctrl.$formatters.unshift(function (a) {
                return $filter(attrs.format)(ctrl.$modelValue)
            });

            elem.bind('blur', function(event) {
                var plainNumber = elem.val().replace(/[^\d|\-+|\.+]/g, '');
                elem.val($filter(attrs.format)(plainNumber));
            });
        }
    };
}]);

这篇关于将货币过滤器应用于angularjs中的输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆