如何使用angularJs从json值呈现HTML标记 [英] How to render a HTML tag from json value using angularJs
问题描述
_ 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屋!