Crocsx
Crocsx

Reputation: 7609

do not allow more then md-maxlength="200"

I have an md-input with a textarea.

I want to be able to limit the amount of character that the user input.

I use md-maxlength but apart from showing a counter... it doesn't limit anything.

I then add a function to limit the length of the input value, but if I go over the limit, it doesn't call my function anymore, actually, he call it but the value is null.

How can I fix this ??

<textarea ng-model="user.title" md-maxLength="5" ng-change="inputLengthLimiter(user.title,5);"></textarea>


  $scope.inputLengthLimiter = (value, maxLength) => {
    console.log(value)
      if(value.length > maxLength){
        value = value.substring(0,maxLength);
      }
    }

https://codepen.io/anon/pen/WLQKNG

Upvotes: 1

Views: 447

Answers (1)

Just code
Just code

Reputation: 13801

Angularjs documentation says that,

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.

means they will set the validation error for this.

You should add maxlength="{{user.maxLength}}" to your textarea to limit the number of text.

Actually the real problem is it will just sets the validation error and because of that your ng-change will get the undefined error too. you can check your console and see there is an errors.

So, your html should look like this

 <textarea ng-model="user.title" ng-maxLength="{{user.maxLength}}"
 maxlength="{{user.maxLength}}" ng-change="inputLengthLimiter(user,user.maxLength);"></textarea>

You can also remove the ng-change after this change as user will be not be allowed to go beyong the max length.

Controller:

angular
  .module('MyApp', ['ngMaterial', 'ngMessages', 'material.svgAssetsCache'])
  .controller('DemoCtrl', function($scope) {
    $scope.user = {
      title: 'Developer',
      maxLength:5
    }; 

  $scope.inputLengthLimiter = (user) => {
    console.log(user.title)
      if(user.title.length > user.maxLength){
        user.title = user.title.substring(0,user.maxLength);
      } 
    }
   $scope.inputLengthLimiter($scope.user)

  })
  .config(function($mdThemingProvider) {

    // Configure a dark theme with primary foreground yellow

    $mdThemingProvider.theme('docs-dark', 'default')
      .primaryPalette('yellow')
      .dark();

  });

Demo

Upvotes: 1

Related Questions