通过指令将数字转换为货币

时间:2014-11-20 20:33:53

标签: angularjs angularjs-directive

我正在尝试将数字转换为货币假设如果用户在文本框中输入5我想要自动更正它,如$ 5.00我正在尝试编写指令但不知道如何使其工作作为指令的第一时间。

(function () {

'use strict';

angular.module('commonModule')
    .directive('srCurreny', function (utilSvc) {
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function (scope, element, attrs, model) {

                element.bind('blur', function (event) {

                    var val = element.val();

                    if (!utilSvc.isEmptyOrUndefined(val)) {

                        var transform = currency + " " + val.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
                        model.$setViewValue(element.val(transform));

                        scope.$apply();
                    }
                });
            }
        };
    });

})();

2 个答案:

答案 0 :(得分:1)

<强> JS

首先在amount中设置Controller

angular.module('commonModule')
    .controller('aController', ['$scope', function (scope) {
        scope.amount = 5;
    }])
    .directive('srCurrency', ['$filter', function ($filter) {
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function (scope, el, attrs, ngModel) {

                function onChangeCurrency () {
                    ngModel.$setViewValue($filter('currency')(ngModel.$viewValue, '$'));
                    ngModel.$render();
                }

                el.on('blur', function (e) {
                    scope.$apply(onChangeCurrency);
                });
        }
    }
}]);

<强> HTML

<div ng-app='app' ng-controller="aController">
    <input type="text" sr-currency ng-model='amount' />
</div>

<强> JSFIDDLE

答案 1 :(得分:0)

我建议使用Angular的内置货币过滤器,或者,如果它不能满足您的需求,您可以创建自己的。

https://docs.angularjs.org/api/ng/filter/currency