angularjs - 不允许超过 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);
}
}
解决方案
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();
});
推荐阅读
- c# - 比较通用的 Nullable 类型
- x86 - x86-64 CPU 寄存器是否在多个内核之间共享?
- python - 你能看到这里有什么问题吗:Python For Loop 将无法运行,'Int not subscriptable'
- javascript - 通过单击按钮 php 将 javascript 数组插入数据库
- c++ - 为什么 std::atomic 中的所有成员函数都有 volatile 和没有 volatile?
- android - 如何让CombinedChart-BarChart平均分布在x轴上?
- hibernate - CriteriaQuery entity.list 有值
- windows - 与 VS2013(Platform Toolkit v120)相比,使用 VS2017(Platform Toolkit v141)构建的相同二进制文件的性能非常低
- c# - 如何从局域网运行 .mdf 数据库?
- r - 根据特定条件在新列中归因变量在不同年份的差异