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

时间:2014-12-02 15:38:44

标签: javascript html json angularjs escaping

我试图将div对象的内部保存为json对象中的一些html,保存它,然后以json的形式接收它,并将html放在div中时能够用作普通的html。 / p>

所以这是我的尝试

$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>

非常感谢任何帮助!谢谢你的阅读。

2 个答案:

答案 0 :(得分:2)

您必须告诉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。

答案 1 :(得分:0)

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

或者你做一个自定义指令,它加载html并将它作为链接函数的一部分绑定到指令。