使用ng-bind-html表示来自JSON数组的html

时间:2014-07-10 10:30:13

标签: html json angularjs

我想从JSON对象的属性呈现HTML标记,并以模态表示它们。

我有这个JSON对象:

{
"fileUploadCategories": [
{
  "id": "Bread",
  "title": "GrandmaBread",
  "info": "Some info text.",
  "restService": "empty",
  "detailedInfo": [ "<h1>Stedsnavn</h1>",
  "",//line break
  "<i>Some text on a new line.</i>",
  "",//line break
  "Some text on the next line again <b>Should be bold.</b>"]
},
 {
    "id": "Cake",
    "title": "My Cake",
    "info": "Info text blah.",
    "restService": "empty",
    "detailedInfo": "<b>Test</b> <br> This is a text on a new line <br> New line"
  }
 ]  
}

在我的html中,我使用带有ng-repeat和ng-bind-html的angularjs将数据绑定到bootstrap模式。这是我的代码:

<div class="panel-group" id="accordion" ng-repeat="fileUpload in fileUploadConfig" >
<div class="panel panel-default" >
    <div class="panel-heading">
        <h3 class="panel-title">{{fileUpload.title}}</h3>
    </div>
    <div class="panel-body">
        <p class="bg-info">{{fileUpload.info}}</p>
        <div class="form-horizontal">
            <button class="btn btn-primary" id="{{fileUpload.id}}HelpBox" style="float:right" data-toggle="modal" data-target="#{{fileUpload.id}}HelpModal">
              Hjelp
            </button>
        </div>
     </div>
</div>
<!-- Modal -->
<div id="{{fileUpload.id}}HelpModal"class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">{{fileUpload.id}}Help</h4>
      </div>
      <div class="modal-body" ng-bind-html="fileUpload.detailedInfo">
        {{fileUpload.detailedInfo.join('\n')}}
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Lukk</button>
      </div>
    </div>
  </div>
</div>
</div>

当我在数组中使用我的html文本时,它不会像我们想象的那样呈现。 (第一个JSON对象)。它在第二个JSON对象中工作正常(只需删除.join('\ n'))。我在数组中表示HTML的原因是,以后更容易更改文本并查看它将如何呈现,而不是将所有内容放在一行中,其中包含html标记,这看起来非常混乱。

有没有比使用数组表示JSON对象中的数据并让它呈现html标签更好的方法?

1 个答案:

答案 0 :(得分:0)

我为你创建了一个sample,以便可视化正在发生的事情。如您所见,将angularjs标记应用于数组数据类型会导致呈现“stringified”数组:

<div>{{fields.test}}</div> => ["a","b","c"]

现在,我怀疑使用数组是个好主意。在语义上这是不正确的,并且非常令人困惑。只需在JSON中对您的html进行编码,然后对其进行解码(称为sanitize in angular,see more here):

function MyControllerHtml($scope, $sce) {
    $scope.renderHtml = function(value) {
        return $sce.trustAsHtml(value);
    };
    $scope.html = '<h1>Stedsnavn</h1><br/><i>Some text on a new line.</i><br/>Some text on the next line again <b>Should be bold.</b>';
};

<div ng-controller="MyControllerHtml">
    <div ng-bind-html="renderHtml(html)"></div>
</div>

最后,如果您仍想保留数组,则使用angular指令将数组绑定到hml