user3214545 user3214545 - 5 months ago 18
AngularJS Question

Angularjs: return remaining characters in textarea

I am new to Angualrjs. I am trying to display the remaining characters in a textarea.

<textarea ng-model="message" ng-maxlength="100"></textarea>
<div id="characters" ng-model="message"><span>Characters left: {{remaining()}}</span> </div>

And this is the function:

this.scope.remaining = function() {
return this.scope.maxlength - this.scope.message.length;}

The error I am getting is:

Error: Error while interpolating: Characters left: {{remaining()}} TypeError: this.scope is undefined

Can anyone help?


I think you're probably making this more complicated than it needs to be. Try this:

In your controller:

.controller('myCtrl', function($scope /* other dependencies here */){
    $scope.maxLength = 100; // this is the max # of chars allowed in the textarea

In your html:

<textarea ng-model="message" ng-maxlength="{{maxLength}}"></textarea>
<div id="characters">
    <span>Characters left: {{maxLength - message.length}}</span>

The two-way binding for {{maxLength - message.length}} will be instantly updated with the correct number of characters remaining when the user types in the textarea.