2014-11-20 71 views
-1

我想将数字转换为货币假设,如果用户在文本框中输入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(); 
        } 
       }); 
      } 
     }; 
    }); 

})(); 
+0

过滤器通常最好为简单的文本操作,它甚至存在一个[货币角度滤波器(HTTPS://文档。 angularjs.org/api/ng/filter/currency) – JimL 2014-11-20 20:52:16

+0

但是我想在用户移到下一个字段后立即更改它。 – Ahmad 2014-11-20 20:55:36

回答

1

JS

坐落在Controller第一amount

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

+0

非常感谢,这就是我一直在寻找的 – Ahmad 2014-11-21 15:38:36