Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

javascript - Apply currency filter to the input field in angularjs

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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));
            });
        }
    };
}]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...