Home  >  Article  >  Web Front-end  >  Example of how to cancel escaping of HTML fragments in AngularJS_AngularJS

Example of how to cancel escaping of HTML fragments in AngularJS_AngularJS

WBOY
WBOYOriginal
2016-05-16 16:22:221125browse

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

Copy code The code is as follows:

Error: [$sce:unsafe] Attempting to use an unsafe value in a safe context.

HTML fragments need to be marked as trusted using $sce.trustAsHtml(html_in_string) before they can be unescaped using data-ng-bind-html="html_in_string".

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

Copy code The code 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
Copy code The code is as follows:


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn