tonymx227
tonymx227

Reputation: 5451

Get short text of HTML string using AngularJS

I'd like to get the text of an HTML string using AngularJS filters but it seems not working with my code.

My code :

app.filter('unsafe', function($sce) {
    return $sce.trustAsHtml;
});

app.filter('short', function() {
    return function(short, length) {
        return short.substr(0, length || 20)+'...';
   }
});

My template :

<p ng-bind-html="event.description | unsafe | short"></p>

Edit #1 :

Error: [$injector:unpr] Unknown provider: unsafeFilterProvider <- unsafeFilter

Upvotes: 1

Views: 631

Answers (2)

ccjmne
ccjmne

Reputation: 9618

Simply put, here's your problem:
$sce.trustAsHtml does not return a string, and thus, the returned object does not have the substr prototype function you're trying to use in your short filter, after unsafe.

Here's a quote from AngularJS's documentation for $sce.trustAs:

[...] returns an object that is trusted by angular for use in specified strict contextual escaping contexts [...] that uses the provided value.

Just make it:

<!-- "short" filter before "unsafe" -->
<p ng-bind-html="event.description | short | unsafe"></p>

... instead of:

<p ng-bind-html="event.description | unsafe | short"></p>

... and you're good to go!

Here's a working JSFiddle for illustration.

Upvotes: 4

İsmail Şener
İsmail Şener

Reputation: 423

AngularJS filters got 2 arguments which is input and $scope

app.filter('customFilter', function () {
  return function (input, scope) {
    var manipulatedInput = (input * 2) / 5;
    return manipulatedInput;
  };
});

You can got them like this snippet. Hope it helps!

Upvotes: -1

Related Questions