Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 344
GeneralCan Avatar asked Feb 18 '26 14:02

GeneralCan


1 Answers

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

like image 124
PSL Avatar answered Feb 20 '26 02:02

PSL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!