1

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

2 Answers 2

4

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.

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

4 Comments

But also, be mindfull, because allowing HTML and just cutting it off could be quite dangerous for your layout. So I would actually advise against allowing HTML in this case.
Ok, and Is that possible to get only the text using something like $('p').text() with jQuery?
I just watched the JSFiddle, and simply added some lorem, only the three dots were bold, so there seems to be no (real) issue. You should indeed be able to just show the text using angular.element(short).text().substr(0, 20) + '&hellip;'
I just updated the fiddle with some extra checks: jsfiddle.net/dhvo3pf4/1
-1

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.