Limit the length of a string with AngularJS
Solution 1:
Here is the simple one line fix without css.
{{ myString | limitTo: 20 }}{{myString.length > 20 ? '...' : ''}}
Solution 2:
Edit
The latest version of AngularJS
offers limitTo
filter.
You need a custom filter like this:
angular.module('ng').filter('cut', function () {
return function (value, wordwise, max, tail) {
if (!value) return '';
max = parseInt(max, 10);
if (!max) return value;
if (value.length <= max) return value;
value = value.substr(0, max);
if (wordwise) {
var lastspace = value.lastIndexOf(' ');
if (lastspace !== -1) {
//Also remove . and , so its gives a cleaner result.
if (value.charAt(lastspace-1) === '.' || value.charAt(lastspace-1) === ',') {
lastspace = lastspace - 1;
}
value = value.substr(0, lastspace);
}
}
return value + (tail || ' …');
};
});
Usage:
{{some_text | cut:true:100:' ...'}}
Options:
- wordwise (boolean) - if true, cut only by words bounds,
- max (integer) - max length of the text, cut to this number of chars,
- tail (string, default: ' …') - add this string to the input string if the string was cut.
Another solution: http://ngmodules.org/modules/angularjs-truncate (by @Ehvince)
Solution 3:
I know this is late, but in the latest version of angularjs (I'm using 1.2.16) the limitTo filter supports strings as well as arrays so you can limit the length of the string like this:
{{ "My String Is Too Long" | limitTo: 9 }}
which will output:
My String