【问题标题】:preventing maxLength on a input type number防止输入类型号上的 maxLength
【发布时间】:2016-10-12 17:26:10
【问题描述】:

我花了一段时间才弄清楚这一点,但是有人可以发布一种更简洁的方法来限制输入 type='number' 中的位数。问题之一是如果 $scope.variable = null....在输入字段中没有任何意义,则会引发错误。

<input type="number" model='modalName' ng-change="monitorLength('modalName',16)">

JS:

  $scope.monitorLength = function (model,maxLength) {
    if ($scope[model] != null) {  // prevent error on empty input field
      var len = $scope[model].toString() ;  // convert to a string
      if (len.length > maxLength) {  //evaluate string length
        $scope[model] = parseInt(len.substring(0, maxLength));  
        // convert back to number or warning is thrown on input value not being a number
      }
    }
  }

然后我需要对此进行扩展以仅考虑数字,防止任何非数字字符包括“。”和“,”符号:

  var reg = new RegExp(/^\d+$/) ;
  $scope.monitorLength = function (modal,maxLength) {
    if ($scope[modal] != null) {
      var len = $scope[modal].toString() ;
      if (len.length > maxLength) {
        $scope[modal] = parseInt(len.substring(0, maxLength));
      } else if (!reg.test(len)) {
        $scope[modal] = parseInt(len.substring(0, len.length-2));
      }
    }
  }  

有没有办法提取负责调用 ng-change 的 ng-modal?所以呼叫只需:ng-change="monitorLength(10)"。然后在函数中以某种方式动态检索调用 ng-modal?

【问题讨论】:

  • 你不能只在输入元素上使用min 和max attributes 吗?很少有浏览器不支持该功能
  • 不适用于 Angular,因为它包装元素并将它们绑定到 $scope 特定的 HTML 输入参数不起作用或被忽略。

标签: angularjs input maxlength


【解决方案1】:

有没有办法提取负责调用 ng-change 的 ng-modal?

是的。您可以定义一个指令并要求ngModelController。

.directive('maxNum', function(){
    return {
        require: '^ngModel',
        link: function($scope, elem, attrs){
            // here you can add formatters/parsers to the ngModel 
            // to affect the change on the ngModel.$viewValue.

        }
    }
})

正如@rolinger 在另一个答案中所说,使用内置指令不会阻止使用输入无效字符,它们只是将模型标记为无效。

【讨论】:

    【解决方案2】:

    这是一种更简洁的限制数量的方法,为此使用 ngMaxlength:

    <input type="number" model='modalName' ng-maxlength="16">
    

    您可以找到更多属性和信息here

    【讨论】:

    • 你链接到的页面不是ng-maxlength吗?
    • 抱歉从图表复制粘贴,你是对的它的 ng-maxlength
    • 不,ng-maxlength 实际上不会阻止用户输入超过 16 个字符。 $scope.variable 中只存储了 16 个字符...但在视觉上用户仍会看到超过 16 个字符。以上是防止实际输入字段中字符溢出的方法。
    • 来自角度文档:Note: This directive is also added when the plain maxlength attribute is used, with two differences: ngMaxlength does not set the maxlength attribute and therefore HTML5 constraint validation is not available.
    猜你喜欢
    • 2021-01-02
    • 2013-11-26
    • 2018-01-31
    • 2019-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    • 2015-10-13
    相关资源
    最近更新 更多