在Javascript字符串文字中解释HTML标记

时间:2013-08-15 03:25:24

标签: javascript html json angularjs

我进行了一个AJAX调用,它在JSON对象中提供了一个字符串,其中包含如下格式的文本:

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.

我使用此字符串填充网页上的div,使其显示如下:

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

但是,当使用该文本填充div时,我会得到确切的字符串,这意味着<br>显示为文本。我希望他们实际执行他们的功能并打破界限。有没有办法强制浏览器在字符串中解释HTML?

我正在使用Angular来获取数据并填充div,如果这有任何区别的话。

2 个答案:

答案 0 :(得分:6)

这不是直截了当的。您需要使用ngBindHtml

控制器

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

HTML

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

您需要以下模块:

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

请务必将ngSanitize声明为模块依赖,如下所示:

var app = angular.module('angularjs-starter', ["ngSanitize"]);

答案 1 :(得分:4)

您可以使用ng-bind-html-unsafe

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

Demo