How to show text length even if it exceed ng-maxlength?

296 views Asked by At

I am not able to see character count which ng-maxlength reached.

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>

2

There are 2 answers

0
John Smith On

That's because after you've exceeded maxlength, myChar's $modelValue will be undefined. You can still use the $viewValue property as shown in the below example.

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
  $scope.test = function() {
    console.log($scope.form.myChar.$viewValue.length);  
  }
});
<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>

0
Diego Polido Santana On

Just improving the @John Smith's answer:

You could put his verification directly on your html expression. Then you could style it with some CSS to show the user that the length is invalid:

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>