Search code examples
javascriptruby-on-railsangularjsangularjs-limitto

How to limit the characters of a string using AngularJS


I want to limit the number of characters that are displayed when "ng-repeat" displays JSON data. This app is using AngularJS inside the RoR framework. Currently I have the following code which displays each "item.description" but does not limit the number of characters in the string to a length of 25.

HTML:

<div ng-controller="MyController">
  <ul>
    <li ng-repeat="item in artists">
     {{item.description | limitTo:25}}
    </li>
  </ul>
</div>

Controller:

var myApp = angular.module('myApp', []);

myApp.controller("MyController", function MyController($scope, $http){
$http.get("/assets/data.json").success(function(data){
    $scope.artists = data;
  });

I also tried putting the "limitTo:" option inside "ng-repeat" but that limited the amount of "item.description(s)" being displayed, and did not limit the string/content. I followed these instructions for this problem: https://docs.angularjs.org/api/ng/filter/limitTo


Solution

  • There is a better way to do this

    add a property to string's prototype object, to truncate a string

    /**
     * extends string prototype object to get a string with a number of characters from a string.
     *
     * @type {Function|*}
     */
    String.prototype.trunc = String.prototype.trunc ||
    function(n){
    
        // this will return a substring and 
        // if its larger than 'n' then truncate and append '...' to the string and return it.
        // if its less than 'n' then return the 'string'
        return this.length>n ? this.substr(0,n-1)+'...' : this.toString();
    };
    

    and this is how we use it in HTML

    .....
    <li ng-repeat="item in artists">
         // call the trunc property with 25 as param 
         {{ item.description.trunc(25) }}
    </li>
    .....
    

    here is a DEMO