moughamir moughamir - 1 month ago 12
JSON Question

How to bind and parse HTML content retrieved from database via Json

I'm using AngularJS 1.5.8.

I'm trying to bind

{{card.reading}}
in the view, but the data is rendered as text

html

<div ng-app="myApplication" ng-controller="postController as tarot">
<ul>
<li class="card" ng-repeat="card in tarot">
<img class="card" src="app/images/cards/{{card.value}}.png" alt="card.name">
<article>{{card.reading | unsafe}}</article>
</li>
</ul>
</div>`


JavaScript

var app = angular.module('myApplication', []);
app.controller('postController', function($scope, $http, $filter, $sce) {
$scope.$sce = $sce;
var url = './api.php/tarot';
$http.get(url).success(function(response) {
$scope.tarot = php_crud_api_transform(response).tarot;
});
});
app.filter('unsafe', function($sce){
return $sce.parseAsHtml;
});


exemple of JSON

{
"id":1,
"name": "Test",
"value": "1",
"reading": "<h2>Lorem Ipsum</h2><p>Lorem ipsum</p>"
}

Answer

Updating your HTML as such should do the trick..

<div ng-app="myApplication" ng-controller="postController as tarot">
      <ul>
       <li class="card" ng-repeat="card in tarot">
          <img class="card" src="app/images/cards/{{card.value}}.png" alt="card.name">
          <article ng-bind-html="card.reading"></article>
       </li>
      </ul>
</div>`