保存(转义?)html 并在 json 对象中使用它

Saving (escaped?) html and using it in a json object

本文关键字:对象 json 并在 转义 html 保存      更新时间:2023-09-26

我正在尝试将div对象的内部保存为json对象中的某些html,将其保存,然后将其作为json接收回,并让html在放置在div中时能够用作普通html。

所以这是我的尝试

$scope.contentHere = [
{
  'size' : '',
  'title' : 'Utility Alerts',
  'content' : '<div>test 1</div>',
  'help' : 'Help Text Here',
  'launch' :  true,
  'share' : true,
  'mobile' :  true
},
{
  'size' : 'w3',
  'title' : 'Graph',
  'content' : '&lt;nvd3-stacked-area-chart data=&quot;exampleData&quot; id=&quot;exampleId&quot; showXAxis=&quot;true&quot; showYAxis=&quot;true&quot; showControls=&quot;true&quot; width=&quot;700&quot; height=&quot;200&quot;&gt; &lt;svg&gt;&lt;/svg&gt; &lt;/nvd3-stacked-area-chart&gt;',
  'help' : 'Help Text Here',
  'launch' :  true,
  'share' : true,
  'mobile' :  true
}];

我正常尝试了一个,一个完全转义,两个似乎都只是在页面上呈现为正常文本。我重复了它们,并试图像这样显示 html -

<div class="item gs-w" ng-class="widget.size" ng-repeat="widget in contentHere" >
            <div class="handle"><h5 ng-style="{ 'color' : themeHere.h1 }>{{widget.title}}</h5></div>
                {{widget.content}}
    </div>

将不胜感激任何帮助!感谢您的阅读。

你必须告诉 Angular 将内容绑定为 HTML,如下所示:

<div class="item gs-w" ng-class="widget.size" ng-repeat="widget in contentHere" >
    <div class="handle"><h5 ng-style="{ 'color' : themeHere.h1 }>{{widget.title}}</h5></div>
    <div ng-bind-html="widget.content"></div>
</div>

但是,从 1.2 开始,Angular 附带了启用$sce,这意味着您必须明确告诉 Angular 您信任该 HTML,如下所示:

// You will have to inject $sce in your controller.
$scope.contentHere = $scope.contentHere.map(function(entry){
    entry.content = $sce.trustAsHtml(entry.content);
    return entry;
});

另外,不确定这是否只是一个复制粘贴问题,但是在数组中的第二个对象中,内容以HTML实体编码,您将需要适当的,未编码的HTML。

您应该使用唯一标识符将 html 推送到$templateCache中,然后使用 ng-include 从视图中包含该模板。

或者,您可以创建一个自定义指令,该指令加载html并将其作为链接函数的一部分绑定到指令。