Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

angularjs - Convert number to currency through directive

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

})();
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...