通过指令将数字转换为货币 [英] Convert number to currency through directive
本文介绍了通过指令将数字转换为货币的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将数字转换为货币,假设如果用户在文本框中输入 5,我想自动更正它,例如 5.00 美元,因为我正在尝试编写指令,但不知道如何让它第一次像处理指令一样工作.
(函数(){'使用严格';angular.module('commonModule').directive('srCurreny', 函数 (utilSvc) {返回 {限制:'A',要求:'ngModel',链接:函数(范围、元素、属性、模型){element.bind('blur', function (event) {var val = element.val();if (!utilSvc.isEmptyOrUndefined(val)) {var 变换 = 货币 + " " + val.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");模型.$setViewValue(element.val(transform));范围.$应用();}});}};});})();
解决方案
JS
首先在Controller
中设置amount
.
angular.module('commonModule').controller('aController', ['$scope', function (scope) {范围.金额 = 5;}]).directive('srCurrency', ['$filter', function ($filter) {返回 {限制:'A',要求:'ngModel',链接:函数(范围、el、attrs、ngModel){函数 onChangeCurrency () {ngModel.$setViewValue($filter('currency')(ngModel.$viewValue, '$'));ngModel.$render();}el.on('模糊', 函数 (e) {作用域.$apply(onChangeCurrency);});}}}]);
HTML
<input type="text" sr-currency ng-model='amount'/>
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屋!
查看全文