通过指令数转换货币 [英] Convert number to currency through directive
本文介绍了通过指令数转换货币的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想转换数字成货币的假设,如果用户在文本框中输入5,我想自动更正喜欢为$ 5.00我试图写指令,但不知道如何使它作为指令的拳头时间工作的工作。
(函数(){使用严格的;angular.module('commonModule')
.directive('srCurreny',函数(utilSvc){
返回{
限制:'A',
要求:'ngModel',
链接:功能(范围,元素,ATTRS,型号){ element.bind('模糊',函数(事件){ 变种VAL = element.val(); 如果(!utilSvc.isEmptyOrUndefined(VAL)){ VAR变换=货币++ val.toFixed(2).replace(/(\\ D)(=(\\ d {3})+ \\)/克,?。$ 1);
。模型$ setViewValue(element.val(变换)); 。范围$适用();
}
});
}
};
});})();
解决方案
JS
设置在金额
的控制器
第一。
angular.module('commonModule')
.controller('aController',['$范围,功能(适用范围){
scope.amount = 5;
}])
.directive('srCurrency',['$过滤',函数($过滤器){
返回{
限制:'A',
要求:'ngModel',
链接:功能(范围,EL,ATTRS,ngModel){ 功能onChangeCurrency(){
。ngModel $ setViewValue($过滤器(货币)(ngModel $ viewValue,$));
。ngModel $渲染();
} el.on('模糊',函数(E){
。范围$申请(onChangeCurrency);
});
}
}
}]);
HTML
< DIV NG-应用='应用'NG控制器=aController>
<输入类型=文本SR-NG货币模型='量'/>
< / DIV>
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();
}
});
}
};
});
})();
解决方案
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>
这篇关于通过指令数转换货币的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文