Reputation: 10964
I have an angular expression which resolves to a block of text.
The block of text can be anywhere in size from 1 character to over 3,000. I want to add a limit to the amount of text which displays and hopefully add an ellipses to the end of the text, either with an image or somthing like <div>...</div>
.
What would be the best way to approach this?
Is there an angular way to accomplish this, a filter of some sort perhaps?
Or would a directive be the better way to go?
<div text-length-limit>{{description}}</div>
Upvotes: 2
Views: 5624
Reputation: 14590
You can do that with this:
{{description | limitTo: 5}}<span ng-show="description.length > 5">...</span>
limitTo
limits the string to the desired length (5 here) and if the original string is upper that length display the ...
after first 5 characters.
Upvotes: 5
Reputation: 52837
Filters are well suited for formatting a value to another value but keeping the same type. In this case you want a filter that adds an ellipsis (...) if the length of the string is longer than a given length.
var app = angular.module('app',[]);
app.filter('ellipsis', function() {
return function(val, maxLength) {
if (val && val.toString().length > maxLength) {
return val.toString().substring(0, maxLength) + '...';
}
return val;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.js"></script>
<div ng-app="app">
Type text longer than 5 characters: <input type="text" ng-model="text" /> {{text | ellipsis:5}}
</div>
Upvotes: 2