bluestella bluestella - 4 months ago 39
AngularJS Question

How can you limit the value from input using AngularJS?

I am looking for ways to limit the value inside the input to 4 and process the 4 digit value unto my controller.

<input type="number" class="form-control input-lg"
ng-model="search.main" placeholder="enter first 4 digits: 09XX">
{{ search.main | limitTo:4}}

Answer

Can always make a directive for it:

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" type="number" class="form-control input-lg" ng-model="search.main" placeholder="enter first 4 digits: 09XX">
Comments