Explanation: html tags and content are automatically escaped when Angular. js data is bound. angular. js escaping

Source: Internet
Author: User

Explanation: html tags and content are automatically escaped when Angular. js data is bound. angular. js escaping

AngularJS binds data in the form of strings by default, that is, it does not escape and accept all html tags in your data. This improves security and prevents html Tag injection attacks, however, it is sometimes necessary, especially when reading formatted text from the database, it cannot be normally displayed on the page.

To escape html, you need to use the ng-bind-html attribute in the html Tag bound to the data. This attribute depends on $ sanitize, that is, you need to introduce the angular-sanitize.js file, the ngSanitize service is injected when the module is defined. For example:

Html:

<span ng-controller = "myCtr" ng-bind-html = "htmlStr"></span>

Javascript:

function myCtr($scope){  $scope.htmlStr = '<p style="color:white;background:#f60;"></p>';};

In this way, html escaping can be implemented, but the problem is that the style label will be automatically filtered out because it is considered unsafe by angularJS. To keep this label, you need to enable the non-security mode.

How can we escape html tags for automatically loaded data? There is actually another binding method:

Html:

<div ng-repeat = "article in articles">  <div class="panel-heading">    

Javascript:

success(function(data){  $scope.articles = data;});myApp.filter('trustHtml',function($sce){  return function(input){    return $sce.trustAsHtml(input);  }});

$ Sce is the security processing module provided by angularJS. The $ sce. trustAsHtml (input) method parses the data content in html format and returns it. Add the filter to the data bound to ng-bind-html to automatically escape html tags when loading data.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.