Scipion
Scipion

Reputation: 11888

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.

Upvotes: 0

Views: 4994

Answers (4)

echology
echology

Reputation: 397

It might be that your links have already got the a tags with it so in this case you do not need to re-add the a tags...

In this case do this...

Add this to you scripts (include acc. to your angular version)

<script type="text/javascript" 
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular-
sanitize.min.js"></script>

Add this to your app.js

var app = angular.module('modulename', [ 'ngSanitize']);

And than in your view do this If it is the div that you want the link to attach to...

<div ng-bind-html="i.link"></div>

The above would give you something as this

<div><a href='your link'></a></div>

Upvotes: 0

sara free
sara free

Reputation: 3

Insert ngSanitize as a dependency to you app:

angular.module('myApp', ['ngSanitize'])

But before be ensure that you are including the script angular-sanitize.js. Good luck!

Upvotes: 0

Dominic Scanlan
Dominic Scanlan

Reputation: 1009

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.

Upvotes: 2

Michael Hays
Michael Hays

Reputation: 6908

In the first case, you'll actually want to use:

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

Double braces, not brace-dollar. In the second case, ng-bind-html will require that you have added "ngSanitize" to your module's dependency list.

angular.module('yourAppNameHere', ['ngSanitize'])

Edit:

If you really do want clickable links on the page, then do pretty much what @sreeramu suggested (Though I'd see if you can't find a way to add a nice description):

<p data-ng-repeat='i in links' ><a ng-href="{{i.link}}">{{i.desc}}</a></p>

(Notice that he suggested using ng-href, instead of href. He's right.)

Upvotes: 1

Related Questions