如何使用 angularJs 从 json 值呈现 HTML 标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31333151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:45:35  来源:igfitidea点击:

How to render a HTML tag from json value using angularJs

htmljsonangularjs

提问by Shasha

// json is like this

// json是这样的

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

// HTML

// HTML

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

//Output

//输出

Preamble : <p>test<\/p>

but how to render that tag and display it using angular ?

但是如何呈现该标签并使用 angular 显示它?

//Output should be like this

//输出应该是这样的

 Preamble : test

回答by Rebornix

Instead of passing string to view directly, you should use sce.trustAsHtmlto pre-process the html.

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

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

Then in your view template, use ng-bind-html to handle html binding.

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

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

As you mentioned you have an array of object, it's not that easy to cast them in your controller, you can bind $sceto your $scopethen call trustAsHtmlin your view

正如您提到的,您有一个对象数组,将它们投射到控制器中并不容易,您可以绑定$sce到视图中的$scopethen 调用trustAsHtml

So in your controller

所以在你的控制器中

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

Then in your html view

然后在你的 html 视图中

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

回答by User2

Please check this working example: http://jsfiddle.net/Shital_D/b9qtj56p/6/

请检查这个工作示例:http: //jsfiddle.net/Shital_D/b9qtj56p/6/

Download file - angular-sanitize.js and include it in your app.

下载文件 - angular-sanitize.js 并将其包含在您的应用程序中。

var app = angular.module('myApp', ["ngSanitize"]);       

app.controller('myController', function($scope,$compile) {
    $scope.html = '<p>Your html code</p>';
});

<div ng-app="myApp">
     <div ng-controller="myController">
     <p ng-bind-html="html"></p>
</div>