我正在尝试从 js 中的字符串创建一个 html 元素。
字符串是:"<p class='text-muted'> come and see how good I look </p>".
过去我用 php 通过回显来完成此操作,现在我只使用 angularJS 构建客户端,但我不知道该怎么做。
我尝试将字符串绑定(bind)到页面,但正如预期的那样,它打印了整个字符串,但没有将字符串编码为 html 元素..
我试图在互联网上寻找答案,尤其是在这个社区中,但没有成功......
这可能吗?如果可能,怎么做?
提前致谢
最佳答案
您可以使用 ng-bind-html
指令将 html 字符串绑定(bind)到元素。应该首先清理字符串,例如通过注入(inject) $sce
并在要绑定(bind)的字符串上调用 $sce.trustAsHtml()
。
示例 Controller :
app.controller('MainCtrl', function($scope, $sce) {
$scope.template = $sce.trustAsHtml('<p class="text-muted"> come and see how good I look </p>');
});
在 html 中
<div ng-bind-html="template"></div>
Here's a quick example plunker 可以输入html点击绑定(bind)
关于javascript - 使用js从字符串创建一个html元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45640262/