Angularjs truncate text filter examples. Enter text into the demo below to see the angular truncate filter in action!
ngFilter:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
/** * Truncate Filter * @Param text * @Param length, default is 10 * @Param end, default is "..." * @return string */ 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; } }; }); |
Usage:
1 2 3 4 5 |
<p>{{myText|truncate}}</p> <p>{{myText|truncate:5}}</p> <p>{{myText|truncate:25:" ->"}}</p> |
Recently I wrote and shared on github an AngularJS module for truncating texts. The basic plus of this module is its ability to toggle the truncated texts visible or not.
https://github.com/lorenooliveira/ng-text-truncate
It’s just a couple of lines of JS. But they were useful for me. Maybe they are useful to someone else 🙂
Nice thanks Loreno, However since writing this post I found that you can do this with Underscore.js, in particular string add-on for it. http://epeli.github.io/underscore.string/
Nice filter , super userfull thanks