当您的 textarea 超过 15 个字符时,result
就变成undefined
了——这就是ng-min/maxlength
指令的工作方式。我认为您必须编写自己的指令。这是一个将在 15 个字符后阻止输入的指令:
<textarea my-maxlength="15" ng-model="result"></textarea>
app.directive('myMaxlength', function() {
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
var maxlength = Number(attrs.myMaxlength);
function fromUser(text) {
if (text.length > maxlength) {
var transformedInput = text.substring(0, maxlength);
ngModelCtrl.$setViewValue(transformedInput);
ngModelCtrl.$render();
return transformedInput;
}
return text;
}
ngModelCtrl.$parsers.push(fromUser);
}
};
});
fiddle
更新:允许超过 15 个字符,但当计数超过 15 时禁用提交按钮:
link: function (scope, element, attrs, ngModelCtrl) {
var maxlength = Number(attrs.myMaxlength);
function fromUser(text) {
ngModelCtrl.$setValidity('unique', text.length <= maxlength);
return text;
}
ngModelCtrl.$parsers.push(fromUser);
}
fiddle