首页 > 解决方案 > 不允许超过 md-maxlength="200"

问题描述

我有一个带有文本区域的 md 输入。

我希望能够限制用户输入的字符数量。

我使用md-maxlength但除了显示一个计数器......它没有任何限制。

然后我添加了一个函数来限制输入值的长度,但是如果我超过了限制,它就不再调用我的函数了,实际上,他调用了它,但值为 null。

我怎样才能解决这个问题 ??

<textarea ng-model="user.title" md-maxLength="5" ng-change="inputLengthLimiter(user.title,5);"></textarea>


  $scope.inputLengthLimiter = (value, maxLength) => {
    console.log(value)
      if(value.length > maxLength){
        value = value.substring(0,maxLength);
      }
    }

https://codepen.io/anon/pen/WLQKNG

标签: angularjsangular-material

解决方案


Angularjs 文档说,

ngMaxlength(可选) number 如果值长于 maxlength,则设置 maxlength 验证错误键。将属性设置为负值或非数字值,允许查看任何长度的值。

意味着他们将为此设置验证错误。

您应该添加maxlength="{{user.maxLength}}"到您的 textarea 以限制文本的数量。

实际上真正的问题是它只会设置验证错误,因此您的 ng-change 也会得到未定义的错误。你可以检查你的控制台,看看有没有错误。

所以,你的 html 应该是这样的

 <textarea ng-model="user.title" ng-maxLength="{{user.maxLength}}"
 maxlength="{{user.maxLength}}" ng-change="inputLengthLimiter(user,user.maxLength);"></textarea>

您也可以ng-change在此更改之后删除,因为不允许用户超出最大长度。

控制器:

angular
  .module('MyApp', ['ngMaterial', 'ngMessages', 'material.svgAssetsCache'])
  .controller('DemoCtrl', function($scope) {
    $scope.user = {
      title: 'Developer',
      maxLength:5
    }; 

  $scope.inputLengthLimiter = (user) => {
    console.log(user.title)
      if(user.title.length > user.maxLength){
        user.title = user.title.substring(0,user.maxLength);
      } 
    }
   $scope.inputLengthLimiter($scope.user)

  })
  .config(function($mdThemingProvider) {

    // Configure a dark theme with primary foreground yellow

    $mdThemingProvider.theme('docs-dark', 'default')
      .primaryPalette('yellow')
      .dark();

  });

演示


推荐阅读