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

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...