Marcus Höglund
Marcus Höglund

Reputation: 16811

Set html5 input maxlength attribute with AngularJS

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?

Upvotes: 0

Views: 15557

Answers (3)

Don
Don

Reputation: 1334

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

Upvotes: 1

Jagan C
Jagan C

Reputation: 66

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

Upvotes: 0

Shintu Joseph
Shintu Joseph

Reputation: 962

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

Append ng- to all angular directives.

Upvotes: 0

Related Questions