0

I want to set the maxlength of an input via AngularJS and when the user have reached the maximum characters then no new characters should be added to the input.

I have an input which ng-model is selecteddata.Type.Value

The max character value is stored in selecteddata.Type.MaxLength

I've added the html5 maxlength attribute as below:

<input type="text" ng-model="selecteddata.Type.Value" maxlength="{{selecteddata.Type.MaxLength}}" />

This works as I want to, when the user reach the maximum characters it's not possible to add new but it doesn't set the selecteddata.Type.Value..

Why doesn't this work? Is there a AngularJS way of doing this? I've read about ngMaxlength but it doesn't behave as I want. Do I need to write a custom directive to make this work? Any suggestions?

Marcus Höglund
  • 16,172
  • 11
  • 47
  • 69
  • Directive that do it http://stackoverflow.com/questions/17075969/ng-maxlength-screws-up-my-model – The scion Jun 07 '16 at 14:13
  • ngMaxlength https://docs.angularjs.org/api/ng/directive/ngMaxlength – Max Sorin Jun 07 '16 at 14:14
  • Your example it self seem to work in this fiddle. https://jsfiddle.net/U3pVM/25383/ , Can you let us know how are you checking selecteddata.Type.Value if it is set or not ? – Don Jun 07 '16 at 14:22
  • @Don Thx, I can see that it works in your example. I will update my answer asap with the full template. – Marcus Höglund Jun 07 '16 at 15:33
  • @Don you're right! this works as it is. The selectedData is updated correctly and the error accoured in my json serializing. If you post the fiddle as an answer I will accept it. Many thanks for your time – Marcus Höglund Jun 08 '16 at 05:36
  • I have added my answer. Thanks. – Don Jun 08 '16 at 13:41

3 Answers3

1

The fiddle for my version: https://jsfiddle.net/U3pVM/25383/

  <div ng-app>
      <div ng-controller="TodoCtrl">
       <input type="text" ng-model="selecteddata.Type.Value" maxlength="{{selecteddata.Type.MaxLength}}" />

      selecteddata.Type.Value-{{selecteddata.Type.Value}}
      </div>
    </div>

function TodoCtrl($scope) {
  $scope.selecteddata={
    'Type':{
      'MaxLength':5
    }
  }
}
Don
  • 1,334
  • 1
  • 10
  • 18
0
<input type="text" data-ng-model="selecteddata.Type.Value" data-ng-maxlength="selecteddata.Type.MaxLength" />

Append ng- to all angular directives.

Shintu Joseph
  • 962
  • 7
  • 19
  • 1
    I know, as I wrote in the question, that ngMaxLength exist but it doesnt behave as I want. I want to block characters when the max value is reached which ngMaxLength doesn't do – Marcus Höglund Jun 07 '16 at 14:23
0

you can use AngularJS default attribute, ng-maxlength

    <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" />

Try this PLNKR: https://plnkr.co/edit/6ztQAixx9KkHBO4a3qD3?p=preview

Jagan C
  • 66
  • 12