AngularJS - How to Limit String Length using Filter?

By Hardik Savani | April 14, 2016 | | 8649 Viewer | Category : Javascript jQuery AngularJS


Some case we have enough space to display content, for example you have articale blog and you want to display saveral articale on homepage with limited content like this way :

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod

tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,

quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo

consequat. Duis aute irure dolor in reprehenderit in voluptate....

You can do it easily if you are work on any framework or something, but if you want to do on angular then you need to create your own filter for this. you can set limit of characters using following filter:

Create Filter:

var app = angular.module('myApp', []);

app.filter('limitChar', function () {

return function (content, length, tail) {

if (isNaN(length))

length = 50;

if (tail === undefined)

tail = "...";

if (content.length <= length || content.length - tail.length <= length) {

return content;

}

else {

return String(content).substring(0, length-tail.length) + tail;

}

};

});

Use Filter:

If you don't want to set limit then it will take 50 auto.

{{ randomText | limitChar }}


Bellow example you can see, we can set limit specific as we want.

{{ randomText | limitChar:10 }}


Bellow example you can see, we can set limit specific as well as we can specify last char as we want.

{{ randomText | limitChar:10:"...!!!" }}



Do you want to expert php developer or developer team for your projects ?
Contact US