Escape HTML text in an AngularJS directive

后端 未结 9 891
执念已碎
执念已碎 2020-12-05 07:12

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.

相关标签:
9条回答
  • 2020-12-05 07:54

    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 = {
              "&": "&",
              "<": "&lt;",
              ">": "&gt;",
              '"': '&quot;',
              "'": '&#39;',
              "/": '&#x2F;'
          };
      
          return function(str) {
              return String(str).replace(/[&<>"'\/]/g, function (s) {
                  return entityMap[s];
              });
          }
      });
      
    0 讨论(0)
  • 2020-12-05 07:55

    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 );
    
    0 讨论(0)
  • 2020-12-05 07:58

    You can implement filter like this:

    app.filter('escape', escape);
    
     function escape() {
        return function (html) {
          return angular.element('<pre/>').text(html).html();
        };
      }
    
    0 讨论(0)
提交回复
热议问题