Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit the length of a string with AngularJS

Here is the simple one line fix without css.

{{ myString | limitTo: 20 }}{{myString.length > 20 ? '...' : ''}}

Edit The latest version of AngularJSoffers limitTo filter.

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)


I know this is late, but in the latest version of angularjs (I'm using 1.2.16) the limitTo filter supports strings as well as arrays so you can limit the length of the string like this:

{{ "My String Is Too Long" | limitTo: 9 }}

which will output:

My String

You can simply add a css class to the div, and add a tool tip via angularjs so that trimmed text will be visible on mouse over.

<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;
   }

I had a similar problem, here is what i did:

{{ longString | limitTo: 20 }} {{longString.length < 20 ? '' : '...'}}