user2456259
user2456259

Reputation: 157

Shortening a String in Angular JS

I have multiple titles that are longer than 40 characters. I would like to shorten it to 40 characters and add ... if there are more characters.

I want to do something like this but in angular js:

if ( title.length > 40){
title = title.substring(0, 40) + '...'
}

Upvotes: 0

Views: 585

Answers (2)

StuR
StuR

Reputation: 12218

I'd suggest create an angular filter, something like this:

angular.module("myApp", [])
.filter('ellipsis', function () {
    return function (input, chars) {
        return input.length > chars ? input.substring(0, chars) + '...' : input;
    };
});

function myCtrl($scope) {
    $scope.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed interdum urna vitae nisl volutpat mattis.";
}

Usage example:

<div ng-controller="myCtrl">
    {{ text | ellipsis:40 }}
</div>

http://jsfiddle.net/rd13/KLDEZ/4/

Upvotes: 2

Mark
Mark

Reputation: 92440

If you are looking for something a little more 'angular-y' you could write a filter that would allow you to use this in templates:

{{title | shorten:25}}!

Here's a super-basic fiddle with an example. You might want to add some error-catching, testing, etc:

Upvotes: 0

Related Questions