Ecco un filtro personalizzato per troncare il testo. È ispirato alla soluzione di EpokK ma modificato per le mie esigenze e gusti.
angular.module('app').filter('truncate', function () {
return function (content, maxCharacters) {
if (content == null) return "";
content = "" + content;
content = content.trim();
if (content.length <= maxCharacters) return content;
content = content.substring(0, maxCharacters);
var lastSpace = content.lastIndexOf(" ");
if (lastSpace > -1) content = content.substr(0, lastSpace);
return content + '...';
};
});
Ed ecco i test unitari in modo da poter vedere come dovrebbe comportarsi:
describe('truncate filter', function () {
var truncate,
unfiltered = " one two three four ";
beforeEach(function () {
module('app');
inject(function ($filter) {
truncate = $filter('truncate');
});
});
it('should be defined', function () {
expect(truncate).to.be.ok;
});
it('should return an object', function () {
expect(truncate(unfiltered, 0)).to.be.ok;
});
it('should remove leading and trailing whitespace', function () {
expect(truncate(unfiltered, 100)).to.equal("one two three four");
});
it('should truncate to length and add an ellipsis', function () {
expect(truncate(unfiltered, 3)).to.equal("one...");
});
it('should round to word boundaries', function () {
expect(truncate(unfiltered, 10)).to.equal("one two...");
});
it('should split a word to avoid returning an empty string', function () {
expect(truncate(unfiltered, 2)).to.equal("on...");
});
it('should tolerate non string inputs', function () {
expect(truncate(434578932, 4)).to.equal("4345...");
});
it('should tolerate falsey inputs', function () {
expect(truncate(0, 4)).to.equal("0");
expect(truncate(false, 4)).to.equal("fals...");
});
});