Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape HTML text in an AngularJS directive

Tags:

angularjs

Is there an angular JS command that will do HTML escaping on text? I am processing a custom directive and have need to escape some of the output which it generates.

Internally the AngularJS sanitzer uses a encodeEntities function, but does not expose it. I know I could duplicate the function, but it seems like there should be a standard way of doing this.


Use-Case: I have a custom directive which does language localization. This directive uses a key lookup from a data file to find language text. In some cases this text is allowed to contain HTML, and/or the directive produces HTML to improve the resulting visual formatting. In addition this directive takes Angular expressions as parameters and uses them as replacements for tokens in the strings. I need to encode these parameters as they may not be HTML safe.

The directive is called as an attribute, for example i18n-html='welcome_text_html,1+1,user.name'. The directive then formats the string as described and uses element.html to update the DOM node.

like image 340
edA-qa mort-ora-y Avatar asked Jan 22 '13 15:01

edA-qa mort-ora-y


People also ask

Does angular escape HTML?

Angular automatically escapes data if you use ng-bind or the {{ curly brace syntax }} . This means it outputs the literal characters instead of interpreting them as HTML.

What is escaping HTML?

Escaping in HTML means, that you are replacing some special characters with others. In HTML it means usally, you replace e. e.g < or > or " or & . These characters have special meanings in HTML. Imagine, you write <b>hello, world</b> And the text will appear as hello, world.

What is $$ in AngularJS?

The $ in AngularJs is a built-in object.It contains application data and methods.


2 Answers

This answer is about escaping, not sanitizing HTML. There are two approaches:

  1. As mentioned by @maniekq, if you can work on the DOM, do:

    element.text( scope.myValue ); 
  2. From this answer, you can use this code from mustache.js and e.g. create an angular filter:

    angular.module('myModule').filter('escapeHtml', function () {      var entityMap = {         "&": "&amp;",         "<": "&lt;",         ">": "&gt;",         '"': '&quot;',         "'": '&#39;',         "/": '&#x2F;'     };      return function(str) {         return String(str).replace(/[&<>"'\/]/g, function (s) {             return entityMap[s];         });     } }); 
like image 188
mb21 Avatar answered Sep 19 '22 23:09

mb21


Sanitizing is one thing, but to display all characters and not "execute" HTML code I have used "text" function to set value.

In your directive, to set value, instead of writing:

element.html( scope.myValue ); 

write:

element.text( scope.myValue ); 
like image 44
jozala Avatar answered Sep 18 '22 23:09

jozala