且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-05 21:27:58

不要直接传递字符串来查看,您应该使用 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&gt ; 


// 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>