html - 如何使用 angularJs 从 json 值呈现 HTML 标记

标签 html json angularjs

//json是这样的

"_unparsedString": "<p>test<\/p>"

//HTML

<div>Preamble : '{{item2._unparsedString}}'</div>

//输出

Preamble : <p>test<\/p>

但是如何渲染该标签并使用 angular 显示它?

//输出应该是这样的

 Preamble : test

最佳答案

您应该使用sce.trustAsHtml 而不是直接传递字符串来查看预处理 html。

$scope.bindHTML = $sce.trustAsHtml(item2._unparsedString);

然后在您的 View 模板中,使用 ng-bind-html 来处理 html 绑定(bind)。

<div>Preamble : <div ng-bind-html="bindHTML"></div></div>

正如您提到的,您有一个对象数组,将它们转换到您的 Controller 中并不容易,您可以将 $sce 绑定(bind)到您的 $scope 然后调用 trustAsHtml 在你看来

所以在你的 Controller 中

myapp.controller('mainController', function ($scope, $http, $filter, $sce) {
   $scope.$sce = $sce;
...
}

然后在你的html View 中

<div>Preamble {{$index+1}} : <span ng-bind-html="$sce.trustAsHtml(item1.Preamble._unparsedString)"></span></div>

关于html - 如何使用 angularJs 从 json 值呈现 HTML 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31333151/

相关文章:

html - 影响下一个 DIV 定位的字体大小

html - Chrome 填充错误

jquery - json 具有自动完成功能?

javascript - Angular ng-repeat范围问题

mysql - 在 Google Cloud 上部署移动网络应用

javascript - 如何将查询字符串数据或任何值从 url 传递到 AngularJS 中的 Controller 函数?

html - 如何将 CSS/HTML 搜索框用于 Google 协作平台中带有 Apps 脚本的链接部分?

html - 在容器 div(最小高度 400px)中放置 3 个 div(高度 100%)

javascript - 问题的 JSON 数组格式

javascript - 访问 API 返回 JSON 数组