Convert number to currency through directive

爷,独闯天下 提交于 2019-12-25 18:52:10

问题


I am trying to convert number into currency suppose if user enter 5 in textbox i want to auto correct it like $5.00 for that i am trying to write directive but no idea how to make it work as working on directive for fist time.

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

})();

回答1:


JS

Set the amount in the Controller first.

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




回答2:


I recommend using the build-in currency filter of Angular, or, if that doesn't meet your needs you can create your own.

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



来源:https://stackoverflow.com/questions/27049036/convert-number-to-currency-through-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!