Escape HTML text in an AngularJS directive

后端 未结 9 897
执念已碎
执念已碎 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:39

    This answer is derived from @mb21's. The only thing that is changed is utilizing $sce. So you can use this filter in ng-bind-html, without triggering Error: $sce:unsafe.

    angular
      .module('yourModule', [
        'ngSanitize'
      ])
      .filter('escapeHtml', function ($sce) {
        // Modified by Rockallite: Add $sce.trustAsHtml() to mute "Error: $sce:unsafe"
        // http://stackoverflow.com/a/32835368/2293304
        // http://stackoverflow.com/a/28537958/2293304
        // https://github.com/janl/mustache.js/blob/master/mustache.js#L82
        var entityMap = {
            "&": "&",
            "<": "<",
            ">": ">",
            '"': '"',
            "'": ''',
            "/": '/'
        };
    
        return function(str) {
          return $sce.trustAsHtml(String(str).replace(/[&<>"'\/]/g, function (s) {
              return entityMap[s];
          }));
        }
      });
    

提交回复
热议问题