Angular$compile为带引号的非HTML字符串抛出错误

Angular $compile throws error for non-HTML string with quotes

本文关键字:HTML 字符串 错误 出错 compile Angular      更新时间:2023-09-26

我正试图使用$compile将用户提供的HTML注入指令中。

module.directive('foo', ["$compile", function($compile) {
    return {
        // ...
        link: function($scope, el) {
            // ...
            var userHtml = userConfigObject.content;
            var compiledHtml = $compile(userHtml)($scope);
            myElement.innerContent.html(compiledHtml);
        }
    };
 }]);

我想允许用户注入一个字符串(例如"Let's party!")或一些HTML(例如'<div ng-click="foo()">Click to party!</div>')。

但是,当用户只提供带引号的字符串(或任何其他"无效HTML")时,$compile语句会给出以下错误:

语法错误,无法识别的表达式:Let's party!

(这个错误最终来自jQuery的Sizzle逻辑)。

我能想到的解决这个问题的唯一方法(同时仍然允许非HTML和HTML字符串)是使用它。

var stepHtml = '<div>' + userConfigObject.content + '</div>';

使得CCD_ 5总是接收到有效的HTML字符串。但是,我不希望不必要地将内容包装在div中。

不起作用的解决方案

我事先尝试过转义用户内容(用HTML代码替换引号),但没有成功。

我还试着使用$sanitize,以为它可以转义字符或其他什么,但也没用。

最后,当我使用$interpolate时,ng-click属性不起作用。

关于如何在非HTML字符串上使用$compile,有什么想法吗?还是我看错了方向?

如果用户实际上正在输入ng-click之类的指令,那么您可以看到html中是否包含元素:

var userHtml = userConfigObject.content;
var $tempDiv  = angular.element('<div>').html(userHtml);
if(!$tempDiv.children().length){
  userHtml = $tempDiv 
}
var compiledHtml = $compile(userHtml)($scope);
myElement.innerContent.html(compiledHtml);

如果根目录中有与元素混合的文本节点,那么最好的选择是始终包装在容器中