I'm using ng-repeat
to fill a table. Some elements have a pretty long length, and I'm looking for a way to cut the content into multiple lines, if a specific length is reached.
During research I found Angulars limitTo
, but it does not exactly look like I was looking for.
E.g. hi i'm a long description and oh, a package (org.foo.awesome.stuff)
should convert into hi i'm a long description and oh,'
a package (org.foo.awesome.stuff)
Big thanks in advance.
I'm using ng-repeat
to fill a table. Some elements have a pretty long length, and I'm looking for a way to cut the content into multiple lines, if a specific length is reached.
During research I found Angulars limitTo
, but it does not exactly look like I was looking for.
E.g. hi i'm a long description and oh, a package (org.foo.awesome.stuff)
should convert into hi i'm a long description and oh,'
a package (org.foo.awesome.stuff)
Big thanks in advance.
Share Improve this question asked Jun 22, 2015 at 17:21 WatteWatte 3121 gold badge5 silver badges15 bronze badges4 Answers
Reset to default 6Write a custom filter:
angular.module('filters', []).filter('lineBreaker', function() {
return function(input, breakLength) {
var newString = "";
for (var i = 0; i < input.length; i++) {
newString = newString+input[i];
if (i%breakLength == 0) {
newString = newString+"\n";
}
}
return newString;
};
});
Called like:
{{ expression | lineBreaker: 10 }}
I'm sure there is a more performant way to do this, but it will get the job done.
app.filter("break", function(){
return function(input, length){
return input.match(new RegExp(".{1," + length + "}", 'g')).join("<br/>");
}
});
You can use something like the following to insert a line break every limit
characters:
var a = "hi i'm a long description and oh, a package (org.foo.awesome.stuff)";
var limit = 10;
for (var i = 0; i < a.length; i++) {
if (i % (limit + 1) === 0 && i > 0) {
a = [a.slice(0, i), '\n', a.slice(i)].join('');
}
}
console.log(a);
/** Output:
hi i'm a lo
ng descrip
tion and o
h, a packa
ge (org.fo
o.awesome.
stuff)"
*/
Throw that into a custom filter.
An easier solution would be to use CSS to modify the word-wrap of the text in the elements of a table. e.g.
th {
word-wrap:normal;
}
td {
word-wrap:normal;
}
In addition to this, you would probably have to edit the width of your table elements so that word-wrapping will occur (instead of creating a box as long as your text). This can be simply achieved by editing the css styling as shown in the following code. There are two options (depending on if you want your webpage to be scaleable or not)
Option 1:
th {
width:300px;
}
...
Option 2:
td {
width:10%
}
...
Also noteable about this solution, it DOES NOT break the given string at any word (unless otherwise told to do so). You can read more about word-wrap here.