5

I'm developing an app containing a form which has a text input with ng-model="description". Now I want to validate this text input using ng-maxlength="50" and required. This works fine, but I also want to add a character counter (like 67/50) shown at all times. I'm using the following code to display the counter: {{description.length || 0}}/50

The issue with this, however, is that description.length doesn't return a value when it's greater than 50, because description input is invalid. In my scenario the counter would default to 0/50 when there's no input (and that's fine) but also when input exceeds max length.

I would also like to display my counter in red when the input length's invalid, but that shouldn't be too hard using angular validation css classes.

Of course I could provide custom validation, but I'm positive there's an easier solution.

1 Answer 1

9

Use the form element $viewValue instead like this:

<form name='form'>

  <input type="text" name='description' ng-model='description' ng-maxlength="50">
  {{form.description.$viewValue.length || 0}}/50
</form>

See this plunker

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.