数字格式。我想在没有指令的情况下在 ng-blur 上输入两位小数
我尝试使用工作正常的指令。
define(['angular', 'mainModule'], function(angular, mainModule) {
'use strict';
mainModule.directive('numbformat', ['$filter', function ($filter) {
return {
require: '?ngModel',
link: function (scope, elem, attrs, controller) {
if (!controller) return;
var DECIMAL_COUNT = 2;
if(attrs.decimal){//if require to change decimal value specify declimal value as attribute in HTML
DECIMAL_COUNT = attrs.decimal;
}
controller.$formatters.unshift(function (a) {
return $filter(attrs.numbformat)(controller.$modelValue, DECIMAL_COUNT);
});
//For on Blur of Element manage Decimal and Format issuse
elem.on('blur' , function() {
elem.val($filter(attrs.numbformat)(controller.$modelValue, DECIMAL_COUNT));
});
//For on Focus of Element manage Decimal and Format issuse
elem.on('focus' , function(){
var actVal = $filter(attrs.numbformat)(controller.$modelValue)
elem.val(actVal);
elem[0].select();
});
controller.$parsers.unshift(function (viewValue) {
var plainNumber = viewValue.replace(/[^\d|\-+|\.+]/g, '');
var actVal = plainNumber.toString();
if(actVal.indexOf('.') > -1 || actVal.indexOf('-') > -1){
return plainNumber;
}else{
elem.val($filter(attrs.numbformat)(plainNumber));
}
return plainNumber;
});
}
};
}]);
})
但它给我带来了 IE11 上的性能问题。 因为在每个错误的输入上都会调用指令,所以我在没有指令的情况下尝试它并转换为它
ng-keyup="formatval($event,'ExpStatement.MinVal')"
ng-blur="formatValBlur($event,'ExpStatement.MinVal')"
现在 ng-keyup 将只允许小数或数字 在模糊的情况下,我想强制要求小数点
简而言之,我想转换指令。或任何人帮助我转换或任何可行的解决方案
这个我试过了,但是不行
$scope.formatval = function(event , val){
$scope.val = $filter('number')( parseFloat($scope.val.replace(/[^\d|\-+|\.+]/g, "")) );
}
最佳答案
只允许在文本框中输入数字(更多信息请参见此处,如果不是数字则显示错误 https://docs.angularjs.org/api/ng/input/input%5Bnumber%5D)
<input type="number" name="number" placeholder="number only" required>
在您的 Angular 模糊事件/keyup 函数中,使用常规 javascript 来格式化数字。
$scope.val.toFixed(2);
关于javascript - 数字格式。我想在没有指令的情况下在 ng-blur 上输入两位小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37538171/