gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 21:21:13 25 4
gpt4 key购买 nike

我正在尝试使用 $compile将用户提供的 HTML 注入(inject)指令。

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语句给出以下错误:

Syntax error, unrecognized expression: Let's party!

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

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

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

所以$compile始终接收有效的 HTML 字符串。但是,我不想将内容不必要地包装在 div 中。 .

无效的解决方案

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

我也尝试使用 $sanitize认为它会转义字符或其他东西,但这也不起作用。

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

关于如何使用 $compile 的任何想法在非 HTML 字符串上?还是我看错了?

最佳答案

如果用户实际上输入了指令,例如 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);

如果根中有文本节点与元素混合,那么最好的办法是始终将其包装在容器中

关于javascript - Angular $compile 为带引号的非 HTML 字符串抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38487013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com