如何使用angularJs从json值呈现HTML标记 [英] How to render a HTML tag from json value using angularJs

查看:191
本文介绍了如何使用angularJs从json值呈现HTML标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



 _ unparsedString:< p> test< \ / p> 

// HTML

 < div>序言:'{{item2._unparsedString}}'< / div> 

//输出

 序言:< p>测试< \ / p> 

但是如何呈现该标记并使用角度显示它?

//输出应该是这样的

 序言:test 


解决方案

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

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

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

 < div>前言:< div ng-bind-html =bindHTML>< / div>< / div> 

正如你所提到的,你有一个对象数组,在控制器中投射它们并不那么容易,你可以将 $ sce 绑定到你的 $ scope 然后调用 trustAsHtml 在你看来



所以在你的控制器中

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

然后在您的HTML视图中

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


// json is like this

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

// HTML

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

//Output

Preamble : <p>test<\/p>

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

//Output should be like this

 Preamble : test

解决方案

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

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

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

<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 $sce to your $scope then call trustAsHtml in your view

So in your controller

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

Then in your html view

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

这篇关于如何使用angularJs从json值呈现HTML标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆