在 AngularJS 指令中转义 HTML 文本 [英] Escape HTML text in an AngularJS directive

查看:37
本文介绍了在 AngularJS 指令中转义 HTML 文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个 Angular JS 命令可以对文本进行 HTML 转义?我正在处理一个自定义指令,需要转义它生成的一些输出.

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.

AngularJS sanitzer 在内部使用了 encodeEntities 函数,但没有公开它.我知道我可以复制这个函数,但似乎应该有一个标准的方法来做到这一点.

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.

用例:我有一个进行语言本地化的自定义指令.该指令使用数据文件中的键查找来查找语言文本.在某些情况下,允许此文本包含 HTML,和/或指令生成 HTML 以改进生成的视觉格式.此外,该指令将 Angular 表达式作为参数,并将它们用作字符串中标记的替换.我需要对这些参数进行编码,因为它们可能不是 HTML 安全的.

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.

该指令作为属性调用,例如 i18n-html='welcome_text_html,1+1,user.name'.该指令然后按照描述格式化字符串并使用 element.html 更新 DOM 节点.

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.

推荐答案

这个答案是关于转义,而不是净化 HTML.有两种方法:

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

  1. 正如@maniekq 所提到的,如果您可以处理 DOM,请执行以下操作:

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

element.text( scope.myValue );

  • 来自这个答案,您可以使用这个来自 mustache.js 的代码 和例如创建角度过滤器:

  • 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];
            });
        }
    });
    

  • 这篇关于在 AngularJS 指令中转义 HTML 文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆