限制AngularJS中的小数位数

时间:2018-04-17 10:46:52

标签: angularjs

我试图限制在文本框中输入超过4位小数,有人可以帮我吗?

<input type="text" class="txt" id="txtValue"  ng-model="serviceParam.Value">

重要的是,验证应该在键入时发生,而不是焦点化(标签输出)。

2 个答案:

答案 0 :(得分:0)

<input type="text" class="txt" id="txtValue"  ng-model="serviceParam.Value" onKeyPress="if(this.value.length==5) return false;">

使用下面的代码。如果char是&gt;它将返回false 4

答案 1 :(得分:0)

跟进此代码,它会在四位小数后禁用输入。您需要使用ng-change跟进小数位后的更改。我想这涵盖了你的所有要求。

&#13;
&#13;
<!DOCTYPE html>
<html ng-app="decimal">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.9/angular.min.js"></script>
<body ng-controller="ExampleController">
<input type="text" ng-model="number_value" ng-change="setFourDecimalPlaces()" ng-maxlength={{maxlength}} ng-disabled="disabled" />
{{decimal_change}}
<script>
    angular.module('decimal', [])
    .controller('ExampleController',['$scope', function($scope) {
    $scope.disabled = false;
    $scope.setFourDecimalPlaces = function(){
      $scope.decimal_change = $scope.number_value.split(".");
      if(undefined !== $scope.decimal_change[1] && $scope.decimal_change[1].length) {
          if($scope.decimal_change[1].length >= 4){
            $scope.maxlength = $scope.decimal_change.length
          }
      }
    }
}])
</script>
</body>
</html>
&#13;
&#13;
&#13;