angularjs, ng-model and maxlength: String was not truncated

236 Views Asked by At

If I have this html:

    <input type="text" ng-model="person.name" maxlength="10" />

And this js (angularjs)

   $scope.person = {
       name: "Larger than 10"
   };

What I get, "rendered", is this:

maxlength

But I was expecting that maxlength would truncate the string, as it does when you are typing from scratch (when the input field starts in blank). Check this gif animation:

maxlength doesnt let the user to continue typing

Question: Is there an easy workaround to get what I was expecting?

The problem is that I can't get the model value if it is not a valid length, ie: Send later $scope.person.name through an ajax request

Note: ng-maxlength behaves the same

1

There are 1 best solutions below

0
On

You can create yours own directive

app.directive("limitTo", [function() {
    return {
        restrict: "A",
        link: function(scope, elem, attrs) {
            var limit = parseInt(attrs.limitTo);
            angular.element(elem).on("keypress", function(e) {
                if (this.value.length == limit) e.preventDefault();
            });
        }
    }
}]);

<input limit-to="4" class="" ng-model="person.name" placeholder="">