GeneralCan
GeneralCan

Reputation: 317

How to change maxlength value in angular

I'm very new to angular. Im trying to change the value of maxlength from 300 to say 140 on click. The buttons are loaded using ng-repeat and the first one is the only one that's supposed to change the value to 140, the rest should go back to 300.

here's what I have in my controller:

//character counter
$scope.counter = function() {
    var myEl = angular.element(document.querySelector('.form-control'));
    myEl.attr('maxlength', '150');
};

and my html is this:

 <textarea data-ng-model="view.post.content" ng-trim="false" maxlength="340" class="form-control" style="height: 100px;"></textarea>

Upvotes: 3

Views: 9029

Answers (2)

PSL
PSL

Reputation: 123739

Just use ng-maxlength and bind it to a property on the scope, this will provide validation safety.

Example:-

 <textarea data-ng-model="view.post.content" ng-trim="false" 
            ng-maxlength="maxValue" class="form-control" 
            style="height: 100px;"></textarea>

If you want to really restrict then just use interpolation maxlength={{maxValue}}. i.e

 <textarea data-ng-model="view.post.content" ng-trim="false" 
            maxlength="{{maxValue}}" class="form-control" 
            style="height: 100px;"></textarea>

So initially $scope.maxValue = 340 and then set inside the counter just the value of the property to 150.

Doc

ngMaxlength (optional) number : Sets maxlength validation error key if the value is longer than maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any length.

Example

Upvotes: 8

Abhishek Prakash
Abhishek Prakash

Reputation: 964

Use angular directive ng-maxlength

<textarea data-ng-model="view.post.content" ng-trim="false" ng-maxlength="{{len}}" class="form-control" style="height: 100px;"></textarea>

In your controller

//character counter
$scope.len = 300;
$scope.counter = function() {
  $scope.len = 150;
};

Upvotes: 2

Related Questions