我想删除或修剪输入文本字段中第一个或有效数字之前的零。
我有一个文本字段,并限制用户只能输入数字。当我输入值“0145”时,它应该读为“145”。
<div ng-controller="MyCtrl">
<input type="text" ng-model="number" required="required" numbers-only="numbers-only" />
</div>
JavaScript:
angular.module('myApp', []).directive('numbersOnly', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
// this next if is necessary for when using ng-required on your input.
// In such cases, when a letter is typed first, this parser will be called
// again, and the 2nd time, the value will be undefined
if (inputValue == undefined) return ''
var transformedInput = inputValue.replace(/[^0-9]/g, '');
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
function MyCtrl($scope) {
$scope.number = ''
}
最佳答案
将您的正则表达式更改为:
var transformedInput = inputValue.replace(/^[^1-9]*|[^0-9]/g, '');
关于angularjs - 如何在输入文本字段中的有效数字之前删除零 - angularjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43873336/