9

I created 2 filters in AngularJS autolink and nl2br.

autolink: converts a URL string to an <a> tag with the attributes rel="nofollow" target="_blank". I tried using ngSanitize with the linky filter, but it doesn't add the 2 attributes above to it, nor does it provide a way to do it with the exising API.

nl2br: converts new lines to <br> tags.

I want to apply these 2 filters to {{ comment }} using {{ comment | autolink | nl2br }} in my HTML, but the filters are applied before AngularJS does the HTML escaping which results in the <a> and <br> to be escaped as well. Basically, I want to apply the filters after the escaping took place.

Is there a way to do this with AngularJS?

1 Answer 1

13

If you have a standard interpolation in your HTML, Angular will escape it:

<div> {{ var | filter1 | filter2 }} </div>

The result of the whole expression will be escaped.

What you want is ng-bind-html-unsafe (docs here). You can expression basically the same thing as above as:

<div ng-bind-html-unsafe='var | filter1 | filter2'></div>

Now the result of the expression won't be sanitized, and will be inserted as the contents of the div.

EDIT: Note that there's also ng-bind-html, which will still produce HTML, but will sanitize it first ($sanitize docs).

ng-bind-html lives in the ngSanitize module, so you'll have to make sure that you've declared it as a dependency in your angular.module call.

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

7 Comments

But I want the comment, in my case, to be escaped; with the 2 filters applied after the escaping.
Ah, then use ng-bind-html instead of ng-bing-html-unsafe. I've added that to the answer.
I did do that as stated in my original post. But I want everything escaped THEN apply my filters. ng-bind-html will safely escape some HTML and will leave some basic html tags alone. Also with ng-bind-html, it will remove the href attribute that I am defining with my autolink filter.
ng-bind-html is different from using curly braces. See jsfiddle.net/GqNxT - the href isn't stripped.
Ok, last try, as I think you're misunderstanding me. (1) have some data in $scope.comment. (2). inject $sanitize and sanitize just the comment $scope.sanitizedComment = $sanitize(@scope.comment). (3) Use sanitizedComment in your HTML <div ng-bind-html-unsafe='sanitizedComment | autolink | nl2br></div>. That way you only sanitize the comment, then the filters are applied unsafely, as-is, with ng-bind-html-unsafe.
|

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.