Example _ AngularJS

Source: Internet
Author: User
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:


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.