AngularJS > Filters

Limit characters in AngularJS

How to limit number of characters in AngularJS?


To limit number of characters/array elements from a string/array in AngularJS, we can use limitTo filter.

    <div ng-controller="LimitController">
        <h4>String limit</h4>
        <p>{{ 'TechFunda' | limitTo:4}}</p>        
        
        <h4>Dynamic string limit</h4>
        <p>Example string: <b>{{Characters}}</b> <br />Limit characters to :
        <input type="number" ng-model="CharactersLimit" />
            => {{ Characters | limitTo:CharactersLimit}}        
        </p>

        <h4>String Array limit</h4>
        <p>
            Example Array: <b>{{CharactersArray}}</b> <br />Limit array element to :
            <input type="number" ng-model="CharactersLimitA" />
            => {{ CharactersArray | limitTo:CharactersLimitA}}
        </p>
    </div>
    <script>
        var app = angular.module("app", []);
        app.controller("LimitController", ["$scope", function($scope){
            $scope.Characters = "Tech Funda is how to tutorials website." ;
            $scope.CharactersLimit = 10;

            $scope.CharactersArray = ['Tech','Funda','is','how','to','tutorials','website.'];
            $scope.CharactersLimitA = 3;

        }]);
    </script>

In the first demonstration, we have a static string "TechFunda" and we have applied limitTo:4 characters that shows only 4 characters from 'TechFunda'.

In the second demonstration, we have a long sentence and we are limiting the number of characters to display from that string with the help of a number textbox. If we change the value of the first text box, the number of characters displaying from that string changes.

In the third demonstration, we have a string array and we are limiting the number of element to display with the help of second textbox, as we change the number in the text box, the string elements to display changes.

Output

limitTo filter in AngularJS

 Views: 16045 | Post Order: 28




Write for us






Hosting Recommendations