0

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) + '...'
}
3
  • And? Its not working, or..? Commented Aug 6, 2014 at 22:56
  • I am just looking for a way to do something similar in angular js. Commented Aug 6, 2014 at 22:58
  • 1
    You don't say and I can't figure out exactly why you'd want to do this unless it is to prevent overflow. Have you checked out the css property text-overflow: ellipsis? Commented Aug 7, 2014 at 0:39

2 Answers 2

2

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/

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

Comments

0

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:

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.