Angular.js automatic escape of HTML tags and content during data binding

Source: Internet
Author: User
Tags html form

ANGULARJS data binding By default is the data in the form of a string, that is, the HTML tags in your data are not escaped the full receipt, so as to improve security, prevent the injection of HTML tags attacks, but sometimes need, especially when reading formatted text from the database, cannot be displayed correctly on the page.

To escape HTML, you need to use the Ng-bind-html property in the HTML tag of the data binding, which is dependent on the $sanitize, That is, you need to introduce the Angular-sanitize.js file and inject the service Ngsanitize when the module is defined. Like what:

Html:

<span Ng-controller = "myctr" ng-bind-html = "Htmlstr" ></span>

Javascript:

function Myctr ($scope) {

$scope. htmlstr = ' <p style= ' color:white;background: #f60; " ></p> ';

};

This allows for HTML escaping, but one problem is that the style tag is automatically filtered out by Angularjs, and in order to preserve it, you need to turn on non-secure mode.

How do I let the automatically loaded data escape HTML tags? There is actually a way to bind:

Html:

<div ng-repeat = "article in articles" >

<div class= "Panel-heading" >

</div>

<div class= "Panel-body" >

<article id= "Word-display" ng-bind-html= "article.content | Trusthtml ">

</article>

</div>

</div>

Javascript:

Success (function (data) {

$scope. articles = data;

});

Myapp.filter (' trusthtml ', function ($SCE) {

return function (Input) {

Return $SCE. trustashtml (input);

}

});

Where $sce is the ANGULARJS's own security processing module, the $SCE. trustashtml (Input) method is to parse and return the data contents in HTML form. Adding this filter to the data bound by ng-bind-html enables automatic escaping to HTML tags when data is loaded.

Angular.js automatic escape of HTML tags and content during data binding

Related Article

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.