parse html inside ng-bind using angularJS

All we need is an easy explanation of the problem, so here it is.

I’m having issue with angularJs. My application requests some data from the server and one of the values from the data returned from the server is a string of html. I am binding it in my angular template like this

<div>{{{item.location_icons}}</div>

but as you might expect what I see is not the icons images but the markup
basically the stuff in the div looks like

 "<i class='my-icon-class'/>"

which is not what I want.

anyone know what I can do to parse the html in the transclusion

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You want to use ng-bind-html and ng-bind-html-unsafe for that kind of purpose.

The examples are shown here

Method 2

As ng-bind-html-unsafe is deprecated, you can use this code instead.

You need to create function inside your controller:

$scope.toTrustedHTML = function( html ){
    return $sce.trustAsHtml( html );
}

and use something like this in your view:

<span ng-bind-html='toTrustedHTML( myHTMLstring )'></span>

Don’t forget to inject $sce:

AppObj.controller('MyController', function($scope, $sce) {
    //your code here 
});

Method 3

A better way is to use $compile instead of ng-bind-html-unsafe.

See: http://docs.angularjs.org/api/ng.$compile

Lastly, at the moment, the last version of angularJS (release candidate 1.2.0) do not have any ng-bind-html-unsafe directive. So I really encourage you to consider this option before any future update of your app. ( ng-bind-html-unsafe may/will not working any more…)

http://code.angularjs.org/1.2.0rc1/docs/api/ng.directive:ngBindHtml

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply