使用js从字符串创建html元素

时间:2017-08-11 16:58:38

标签: javascript angularjs

我正在尝试从js中的字符串创建一个html元素。

字符串为:"<p class='text-muted'> come and see how good I look </p>".

过去我用php做了这个回音,现在我只用angularJS构建客户端,我不知道怎么做。

我试图将字符串绑定到页面,但是,正如预期的那样,它打印整个字符串而不将字符串编码为html elemnt ..

我试图在互联网上找一个答案,特别是在这个没有抢救的社区......

是否可能,如果可能,如何?

提前致谢

2 个答案:

答案 0 :(得分:1)

您可以使用ng-bind-html指令将html字符串绑定到元素。首先应该对字符串进行清理,例如通过注入$sce并在要绑定的字符串上调用$sce.trustAsHtml()

控制器示例:

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并单击以绑定它

答案 1 :(得分:0)

您可以使用属性“innerHTML”将html的String定义附加到任何DOM元素。

yourDomEl.innerHTML = '<div class="your-class"><a>Link</a></div>';