Home > Article > Web Front-end > Example of how to cancel escaping of HTML fragments in AngularJS_AngularJS
Today I tried to use Rails as the backend to provide data in JSON format, and AngularJS as the frontend to process JSON data. What AngularJS gets is a piece of HTML text. If you use data-ng-bind directly, it will be escaped. Use data-ng-bind-html to unescape.
But if you use data-ng-bind-html directly, an error will be prompted
Among all the articles that Angular retrieves through API or here, each article has an html_body attribute which is an HTML fragment rendered by Markdown or Org.
After getting JSON data through API, use the angular.forEach method provided by AngularJS to mark the html_body of each post, save the result as trustedBody, and then use data-ng-bind-html="post in HTML .trustedBody" can be unescaped.
AngularJS part
$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();
});