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?

6
  • Directive that do it stackoverflow.com/questions/17075969/… Commented Jun 7, 2016 at 14:13
  • ngMaxlength docs.angularjs.org/api/ng/directive/ngMaxlength Commented Jun 7, 2016 at 14:14
  • Your example it self seem to work in this fiddle. jsfiddle.net/U3pVM/25383 , Can you let us know how are you checking selecteddata.Type.Value if it is set or not ? Commented Jun 7, 2016 at 14:22
  • @Don Thx, I can see that it works in your example. I will update my answer asap with the full template. Commented Jun 7, 2016 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 Commented Jun 8, 2016 at 5:36

3 Answers 3

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
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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

Append ng- to all angular directives.

1 Comment

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.