Scipion Scipion - 4 months ago 24
AngularJS Question

Angularjs convert string to html in view

I am currently trying to add links in my view. I do have links which basically contains html tags as strings.
I tried:

<p data-ng-repeat='i in links' >{$ i.link $}</p>


which basically just deploy in my view : mylink

So I did try:

<p data-ng-repeat='i in links' ><span data-ng-bind-html="i.link"></span></p>


It doesn't work though, any idea how could I achieve this ?

Thanks.

Answer

Add the $sce as a dependancy of the module

angular.module('myApp', ['$sce']);

When getting the links

angular.forEach($scope.links, function(value){
    value.link = $sce.trustAsHtml(value.link);
});

Using Safe Contextual Escaping (docs.angularjs.org/api/ng/service/$sce) and using trustAs delegate you're telling Angular that this value is safe to use within that context. In this example. $sce.trustAsHtml returns an object that angular can trust is safe to as HTML.

Comments