2017-05-09 14 views
2

入力テキストフィールドの最初または有効数字の前にゼロを削除またはトリミングしたい。入力テキストフィールドの有効数字の前に0を取り除く方法 - angularjs

私はテキストフィールドを持っており、数字だけを入力するようにユーザーを制限しています。値を「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 = '' 
} 

JSFiddle

答えて

2
の初めにすべて0に置き換わるだろうにあなたの正規表現を変更し

var transformedInput = inputValue.replace(/^[^1-9]*|[^0-9]/g, ''); 
2

あなたの正規表現は少し間違っています。それは次のようになります。

var transformedInput = inputValue.replace(/^0*/g, '') 

これは、文字列

関連する問題