1

I have a list of objects that have all of the parameters displayed in a table using ng-repeat.

Occasionally, the Title parameter of an object will be very long and therefore makes the table stretch at certain spots. I have tried using filter but I think that would cut off the rows shown in the table, not the characters of a random object parameter.

Is there a way I can truncate this title to a certain length and add "..." at the end? Apologies if this has been asked before but my research found no answers I needed.

1
  • 5
    This should be solved on the css level using text-overflow: ellipsis;. Commented Mar 24, 2016 at 22:17

1 Answer 1

1

You can write a javascript function to force a maximum length of your text:

$scope.forceMaxLength = function(s, maxLength) {
     if(s.length > maxLength) {
         return Array.prototype.slice.apply(s, [0, maxLength-3]).join('') + '...';
     } else {
         return s;
     }
}

Now you can just use this in your angular template:

   <div ng-repeat="item in items">
        <h3>{{ forceMaxLength(item.title, 25) }}</h3>
   </div>

Having said that, using text-overflow: ellipsis; in your css would probably be a better solution.

The reason for this is that text will have a width that's made up of the sum of the width of each character, and the character widths can vary.

These two strings both have thirty-four characters:

iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii

MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM

If you wanted to truncate these strings so they would fit into a given width, you would want the truncate point to be at different positions in the respective strings.

Sign up to request clarification or add additional context in comments.

1 Comment

I really appreciate it, I ended up going with your first suggestion. While I would have preferred to use ellipsis, the styling was affecting the size of the area the text was in and not the text itself. I am really happy with this solution though since any parameter that has that kind of length will now be shortened, making the lines much more visible.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.