Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying filters on outputted HTML for AngularJS

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?

like image 566
ademers Avatar asked Feb 20 '13 19:02

ademers


1 Answers

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.

like image 152
satchmorun Avatar answered Oct 28 '22 07:10

satchmorun