在Javascript字符串字面量中解释HTML标签

3
我发起了一个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。

你如何将 JSON 对象设置到你的 div 中?你尝试过 innerHTML 吗? - Dilantha
你的 div class 缺少引号 ---- 在 lyrics-container 后面但在 > 之前。 - Paul
2个回答

6

这并不是一件直接的事情,你需要使用 ngBindHtml

控制器(Controller)

$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"]);

2
不要在ng-bind-html中使用{{}},因为它是一个表达式。 - Ahsan Shah

4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接