Mr.Web
Mr.Web

Reputation: 7144

AngularJS HTML filter

I have an AngularJS app, I need to have the string to be filtered (with a filter) to show the correct HTML formatting:

This:

$scope.text = "This is <strong>GREAT</strong>";

Needs to be:

This is GREAT

(And other HTML tags, like <br> and so forth should be working)

It should work thru a filter, like:

{{text | toHTML}}

I know about ng-bind-html BUT I need it to work thru a filter and NOT with ng-bind-html.

I found some examples where the filter needs to be constructed for each step (for the <a> there is a code, for <br> another one...)

Is there a way to filter a scope element to handle the HTML formatting?

Upvotes: 0

Views: 215

Answers (3)

charlietfl
charlietfl

Reputation: 171679

Short answer is....this can not be done and is why ngBindHtml exists in the first place

You are asking to change the default internal compiling of {{}} from inserting text nodes to inserting html elements

Regardless of what you define inside {{}} you can't change the fact that it will always be inserted as a text node and any html tags inside it will not be converted to dom elements.

There is a good XSS security reason for this behavior also. By inserting as text it prevents insertion of malicious script, iframe etc from user input or corrupted data sources

Upvotes: 2

tanmay
tanmay

Reputation: 7911

Create a filter that returns $sce.trustAsHtmled input as output.

Something like:

.filter('toHTML', ['$sce', function($sce){
    return function(val) {
        return $sce.trustAsHtml(val);
    };
}])

EDIT: if you can only use {{}} to render, I am afraid this won't help you. Maybe you can create a directive that does the element level modifications for you.

Upvotes: 1

scary_devil
scary_devil

Reputation: 278

Create this filter as below

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

Use the filter like this

<p ng-bind-html="textCmt | unsafe"></p>

Upvotes: 0

Related Questions