Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render a HTML tag from json value using angularJs

// 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
like image 566
Shasha Avatar asked Jul 10 '15 05:07

Shasha


People also ask

How fetch data from JSON to HTML?

The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.

Can I use HTML tags in JSON?

It is possible to write an HTML string in JSON. You just need to escape your double-quotes.


2 Answers

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>
like image 125
Rebornix Avatar answered Oct 06 '22 23:10

Rebornix


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

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

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>

like image 35
User2 Avatar answered Oct 06 '22 23:10

User2