把它放在一个变量中,这样你就可以重用它
<form name="myForm">
<input type="text"
name="myName"
ng-model="name"
ng-minlength="nameConstraint.maxlength"/>
<div ng-messages="myForm.myName.$error" style="color:maroon" role="alert">
<div ng-message="maxlength">Please enter up to {{nameConstraint.maxlength}} characters</div>
</div>
</form>
没有其他办法,maxLength 指令监视属性 maxlength 并使用 $validators 来验证长度。
这是 angular 中 maxlength 的代码指令:
var maxlengthDirective = function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
var maxlength = -1;
attr.$observe('maxlength', function(value) {
var intVal = toInt(value);
maxlength = isNaN(intVal) ? -1 : intVal;
ctrl.$validate();
});
ctrl.$validators.maxlength = function(modelValue, viewValue) {
return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
};
}
};
};