javascriptangularjsformsvalidationangularjs-forms

Angular validators and ng-maxlength use


I've got the following div, which I want to add the bootstrap's class "has-error" if the input length is over 50 characters. This is the HTML:

<div class="form-group" ng-class="{has-error:[formData.titulo.$error]}">

    <label for="inputTitulo">Título</label>
    <input type="titulo" class="form-control" id="inputTitulo" 
           maxlength="50" ng-maxlength="50" ng-model="formData.titulo">

</div>

How can I make this work? I guess when you reach 50 characters, ng-maxlength throws a error, like the $error object, but I have no clue on what object is, how to access it, and if I have to do some more work in the controller or directive.

Any help here? I can't find any "easy" info regarding this issue and Angular validators.

edit 1:

I've seen all your responses, learned something new thanks to you, but this is still somehow not working. It currently is this way:

  <div class="form-group" ng-class="{'has-error': formData.titulo.$error.maxlength}">
    <label for="inputTitulo">Título</label>
    <input type="titulo" class="form-control"  id="inputTitulo" maxlength="50" ng-maxlength="50" ng-model="formData.titulo">
  </div>

Also tested checking the length directly, as one of you suggested. But none of these solutions seem to work: it never adds the has-error class. Why?


Solution

  • To have the errors published on the scope, a form directive is required.

    <div ng-form="form1" ng-class="{'has-error': form1.text1.$error.maxlength}">
      <input name="text1" ng-model="formData.foo" ng-maxlength="50">
    </div>
    

    (Notice that the above uses the name attribute of the input to publish the form data - really, the ngModelController - on the scope)

    So, the above works, and it's preferable if you do form validation. But, if you just need to check the length of some input, you don't have to use form validation - you could just check the model directly:

    <div ng-class="{'has-error': formData.foo.length > 50}>
      <input ng-model="formData.foo">
    </div>