How to Limit the length of a string in Angular JS?
How to Limit the length of a string in Angular JS?
It requires custom channel:
angular.module('ng').filter('cut', function () { return function (value, word wise, 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 (word wise) { 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:' ...'}}
To use this
{{ myString | limitTo: 20 }}{{myString.length > 20 ? '...' : ''}}
An alternate way to do this is use the ng-maxlength
directive which adds a restriction to an input field, and to the validator of the form:
<input type="text" ng-maxlength="number"></input>
<div class="trim-info" tooltip="{{modal.title}}">{{modal.title}}</div>
.trim-info {
max-width: 50px;
display: inline-block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
line-height: 15px;
position: relative;
}
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)