Angularjs: return remaining characters in textarea

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

<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?

+4
source share
4 answers

I think you are probably making it more complicated than it should be. Try the following:

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>
</div>

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 text box.

+12
source

I believe this.scope.remaining is defined in the controller. Instead of using this.scope.remaining, pass $ scope as a dependency and do $ scope.remaining.

jsFiddle, , .

0

, ! , maxLength , .

: https://jsfiddle.net/t1fhppc9/

ng-maxlength ($ scope.maxLength), angular ($ scope.message). (maxLength - message.length) . .

, ( user3214545). , , , .

:

<div ng-controller="myCtrl">
  <textarea
    ng-model="message"
    ng-maxlength="{{ maxLength }}">
  </textarea>
  <div>
    <span>Characters left: {{ remaining() }}</span>
  </div>
  If there are more than {{ maxLength }} characters, then a red border will be shown.
  <div>
    Message: {{ message }}
  </div>
</div>

:

function myCtrl($scope) {
  $scope.maxLength = 5;

  $scope.remaining = function() {
    return $scope.maxLength - angular.element(document).find('textarea')[0].value.length;
  }
}

Here is the fiddle with function: https://jsfiddle.net/zz13p1tm/

Of course, in a more realistic scenario, this will be wrapped in a directive. Both the region and the element will be passed to the directive. Using the selection area, we can also control parameters such as the maximum length required, disabled, and whether other characters should be displayed in the template.

0
source

You need to pass the scope to the function as a parameter.

-1
source

Source: https://habr.com/ru/post/1524265/


All Articles