我有3个HTML输入字段并在项目中使用Angular-JS。我想将输入限制为maxlength,并且如果用户尝试在maxlength输入字段之后尝试不接受该字符并显示消息,则为
要限制字符,我正在使用maxlength并显示消息,我正在使用limit-to。下面的代码显示此消息:“您已达到允许的最大字符数。”默认情况下,即使我尝试设置maxlength = true。 而且app.directive不会将其设置为true或false。 还有一件事,我是Angular js的新手,只想要Angularjs的解决方案。 我已经尝试过此代码:-
<label> First Name <sub class="ReqSymbol">*</sub></label>
<div class="form-field">
<input limit-to="15" class="form-control" name="firstName" ng-model="firstName" ng-maxlength="true" ng-focus="maxlength=true" maxlength="15" required>
<span style="color:red;" ng-cloak ng-show="(myForm.firstName.$touched && myForm.firstName.$invalid) || (myForm.submitAttempt && myForm.firstName.$invalid)" class="help-line">First Name is required.</span>
<span style="color:red;" ng-cloak ng-show="!myForm.firstName.$error.maxlength" class="help-line error-help-line">You have reached the maximum number of characters allowed.</span>
</div>
<label> Last Name <sub class="ReqSymbol">*</sub></label>
<div class="form-field">
<input only-letters-input limit-to="10" class="form-control" ng-maxlength="true" name="lastname" maxlength="10" ng-model="lastname" required>
<span style="color:red;" ng-cloak ng-show="(myForm.lastname.$touched && myForm.lastname.$invalid) || (myForm.submitAttempt && myForm.lastname.$invalid)" class="help-line">Last Name is required.</span>
<span style="color:red;" ng-cloak ng-show=" !myForm.lastname.$error.maxlength" class="help-line error-help-line">You have reached the maximum number of characters allowed.</span>
</div>
//Code for directive:-
app.directive("limitTo", [function () {
return {
restrict: "A",
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
var limit = parseInt(attrs.limitTo);
angular.element(elem).on('keydown', function (e) {
if (this.value.length <= limit) {
debugger;
ctrl.$setValidity('maxlength', true);
}
else {
ctrl.$setValidity('maxlength', false);
}
});
}
}
}]);
每当我尝试在名字中插入第16个字符或 姓氏的第11个字符会在字段下方弹出消息“您已达到允许的最大字符数。”,并且在最大长度后也不应该接受该字符。limit-to也可以用于n个输入< / p>