Truncate Filter for AngularJS

You can truncate the text using angularJS by creating a truncate filter. The truncate filter accepts inputs like text to truncate,maximum length of the text allowed and truncating characters to append to the text (like '...')

Truncate Filter:


Add the following filter in your javascript file.

angular.module('filters', []).
filter('truncate'function () {
    return function (text, length, end) {
        if (isNaN(length))
            length = 10;
 
        if (end === undefined)
            end = "...";
 
        if (text.length <= length || text.length - end.length <= length) {
            return text;
        }
        else {
            return String(text).substring(0, length - end.length) + end;
        }
 
    };
});
Now use the truncate filter in your html code like below

<div id="main">
        <p>{{yourTextHere|truncate}}</p>  /*case:1*/
        <p>{{yourTextHere|truncate:5}}</p> /*case:2*/
        <p>{{yourTextHere|truncate:25:" ->"}}</p> /*case:3*/
</div>

In case 1, we are just using filter and not mentioning any length. So as defined in the filter code, the default length will be taken (10 in our case).

In case 2, we are providing length. So filter will limit the text as per the length mentioned.

In case 3, we are providing length and end. So filter uses this length to truncate the text and appends the given symbol at the end of the truncated text.

In this way we can truncate the text using AngularJS truncate filter.

For more posts on angularJS visit: angularJS



Read more...