我无法看到ng-maxlength
达到的字符数。
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="plunker" ng-controller="MainCtrl">
<form name="form" novalidate>
<input type="text" ng-model="myChar" ng-maxlength="5">
<br>
<h1>Length: {{myChar.length}}</h1>
</form>
</div>
&#13;
答案 0 :(得分:0)
这是因为在您超过maxlength
后,myChar
$modelValue
将被取消定义。您仍然可以使用$viewValue
属性,如下例所示。
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.test = function() {
console.log($scope.form.myChar.$viewValue.length);
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<div ng-app="plunker" ng-controller="MainCtrl">
<form name="form" novalidate>
<input type="text" name="myChar" ng-model="myChar" ng-maxlength="5" ng-keyup="test()">
<br>
<h1>Length: {{myChar.length}}</h1>
</form>
</div>
&#13;
答案 1 :(得分:0)
改善@John Smith的答案:
您可以将他的验证直接放在您的html表达式上。然后你可以用一些CSS来设置它,以向用户显示长度无效:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<style>
.red {
color: red;
}
</style>
<div ng-app="plunker" ng-controller="MainCtrl">
<form name="form" novalidate>
<input type="text" name="myChar" ng-model="myChar" ng-maxlength="5">
<br>
<h1 ng-class="{'red': form.myChar.$viewValue.length > 5}">Length: {{form.myChar.$viewValue.length}}</h1>
</form>
</div>