This article describes how to cancel escaping HTML fragments in AngularJS. In some places where HTML needs to be displayed, you need to cancel AngularJS escaping. This article introduces this method, for more information about how to use Rails to provide data in JSON format at the backend, AngularJS processes JSON data at the front end. In this case, AngularJS obtains HTML text, if data-ng-bind is used directly, it is escaped. If data-ng-bind-html is used, the escape can be canceled.
However, if data-ng-bind-html is used directly, an error is returned.
The Code is as follows:
Error: [$ sce: unsafe] Attempting to use an unsafe value in a safe context.
You must use $ sce. trustAsHtml (html_in_string) to mark the HTML snippets as trust before using data-ng-bind-html = "html_in_string" to cancel escape.
In my example, Angular uses APIs or all articles. Each article has an html_body attribute that is an HTML clip rendered by Markdown or Org.
After obtaining JSON data through APIS, use angular provided by AngularJS. the forEach method marks the html_body of each post, saves the result as trustedBody, and then uses data-ng-bind-HTML = "post. trustedBody "can be escaped.
AngularJS
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 = javassce.trustashtml(post.html _ body );
});
});
};
$ Scope. syncPosts ();
});
HTML section
The Code is as follows: