Character count in textarea AngularJS

1

I need to create a way to show the quantity of characters remaining in a textearea tag of a description for a given profile.

This part is the data entry:

<textarea class="form-control" type="text" 
          name="description_validate" ng-model="group.description" 
          ng-minlength='{{valideDescricao.description_validate.minlength}}' 
          ng-maxlength="{{valideDescricao.description_validate.maxlength}}" 
          ng-required='valideDescricao.description_validate.required' />

This is another part of my data visualization:

<td align="justify" style="width: 500px"  data-title="'Descrição'" filter="{description: 'text'}" >{{row.description}}</td>

I want to know if there is any way to do the operation with Angular without having to do a whole function in JavaScript, if there is any directive to do this functionality, or a default form in controller and in view .

    
asked by anonymous 10.04.2017 / 15:38

2 answers

1

There is yes, in your case it would be:

<textarea class="form-control" type="text" 
          name="description_validate" ng-model="group.description" 
          ng-minlength='{{valideDescricao.description_validate.minlength}}' 
          ng-maxlength="{{valideDescricao.description_validate.maxlength}}" 
          ng-required='valideDescricao.description_validate.required' />

<span>{{valideDescricao.description_validate.maxlength - group.description.length}} restantes</span>

* If you are using angularJS 1.1.1 or a newer version you need to add ng-trim="false" to textarea , here's an example:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><bodyng-app><textareang-model="txtarea" ng-trim="false" maxlength="200"></textarea>
    <span>{{200 - txtarea.length}} caracteres restantes</span>
</body>
    
10.04.2017 / 15:41
1

No external components required. However you need to expand the default behavior of ng-model , since it does not propagate the properties of the element, maxlength between them:

angular.module('myApp', [])
.directive('ngModel', function attributeNgModelDirective() {
  return {
    require: 'ngModel',
    link: function(scope, el, attrs, ctrl) {
      ctrl.attributes = attrs; //adiciona os atributos do elemento como uma
                               // propriedade do modelo
    }
  };
})
.controller('myController', function($scope){});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script><divng-app="myApp">
  <form name="meuForm">
    <div ng-controller='myController'>
       <input name="entrada" id="entrada" ng-model="description" ng-minlength="2" ng-maxlength="200" />
       <br/>
       <span>Caracteres restantes: {{meuForm.entrada.attributes.maxlength - meuForm.entrada.$viewValue.length}}</span>
       <pre>{{meuForm.entrada | json }}</pre>

    </div>
  </form>
</div>
    
10.04.2017 / 15:52