javascript - 使用js从字符串创建一个html元素

标签 javascript angularjs

我正在尝试从 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/

相关文章:

javascript - 将平面数组减少为 2 层嵌套 json 对象数组

javascript - 当函数是递归Javascript时如何返回父函数

javascript - 理解 TypeScript/Angular JS 中的定义顺序

angularjs - ui-bootstrap 分页在初始化时重置当前页面

javascript - Raphael JS - 在鼠标悬停期间开始/继续动画。鼠标移出时暂停动画

javascript - Nodegit 如何获取新的分支列表?

angularjs - 错误 : [$injector:unpr] Unknown provider: $q. 对 DI 语法感到困惑

javascript - 将 AngularJS 数据保存在内容 div 中

javascript - 如何检查 Mongoose 中是否存在值

javascript - 混合应用程序 : Change HTTP user agent header with AngularJS