Today, I tried to use Rails as the backend to provide JSON format data. AngularJS is used to process JSON data on the front end. When AngularJS gets a piece of HTML text. If you use data-ng-bind directly, it is escaped. Using data-ng-bind-html can cancel the escape.
However, if you use data-ng-bind-html directly, you will prompt an error
The code copy is as follows:
Error: [$sce:unsafe] Attempting to use an unsafe value in a safe context.
HTML fragments need to be marked as trust using $sce.trustAsHtml(html_in_string) before they can be unescaped using data-ng-bind-html="html_in_string".
Among all the articles I took through the API or through Angular, each article has an html_body attribute that is an HTML fragment rendered by Markdown or Org.
After getting JSON data through the API, use the angular.forEach method provided by AngularJS to mark the html_body of each post and save the result as trustedBody, and then use data-ng-bind-html="post.trustedBody" in HTML to cancel the escape.
AngularJS part
The code copy is as follows:
Blog.controller('PostsController', function ($scope, $http, $sce) {
$scope.posts = [];
$scope.syncPosts = function () {
var request = $http.get('http:/localhost:3000/posts.json');
request.success(function (response) {
$scope.posts = angular.forEach(angular.fromJson(response), function (post) {
post.trustedBody = $sce.trustAsHtml(post.html_body);
});
});
};
$scope.syncPosts();
});
HTML Part
The code copy is as follows:
<div data-ng-bind-html="post.trustedBody"></div>