Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpreting HTML Tags in Javascript String Literal

I make an AJAX call that gives me a string within a JSON object containing text formatted like this:

Your girl was in Berkeley with a communist reader. <br> Mine was entombed within boombox and walkman. <br> I was a hoarder, but girl, that was back then. <br> The gloves are off, the wisdom teeth are out. <br> What you on about? <br> I can feel it in my bones. <br> I can feel it in my bones. <br> I'm stronger now, I'm ready for the house. <br> Such a modest mouse. <br> I can't do this alone.

I use this string to populate a div on my webpage, such that it appears like this:

<div class="lyrics-container>{{ the text in the JSON string }} </div>

However, when populating the div with that text, I get the exact string, meaning that the <br>s show up as text. I want them to actually perform their function and break the line. Is there a way to coerce the browser into interpreting HTML within a string?

I'm using Angular to grab the data and populate the div if that makes any difference.

like image 619
user1427661 Avatar asked Aug 14 '26 16:08

user1427661


2 Answers

It is not straight forward. You need to use ngBindHtml.

Controller

$scope.content = "<b>this is bold content</b>";

HTML

<div ng-bind-html="content"></div>

You'll need the following module:

http://code.angularjs.org/1.0.3/angular-sanitize.js

Be sure to declare ngSanitize as a module dependancy, like this:

var app = angular.module('angularjs-starter', ["ngSanitize"]);
like image 191
Ahsan Shah Avatar answered Aug 16 '26 05:08

Ahsan Shah


You can use ng-bind-html-unsafe.

<span ng-bind-html-unsafe="content"></span>

Demo

like image 41
zs2020 Avatar answered Aug 16 '26 05:08

zs2020



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!