【问题标题】:How do I display html coming from a json list in AngularJS?如何在 AngularJS 中显示来自 json 列表的 html?
【发布时间】:2014-07-26 13:56:36
【问题描述】:

拥有一组json信息,例如

[
    {
    "title":"Title 1",
    "description":"<p>Some HTML</p>"
    },
    {
    "title":"Title 2",
    "description":"<p>Some HTML</p><p>More HTML</p>"
    }
]

如何在模板中显示 html。目前 html 没有被解码。 我尝试使用下面的代码,但它不起作用。

{{item.title}}
<div data-ng-bind-html='item.description'></div>

控制器看起来像

var searchApp = angular.module('searchApp', ['ngSanitize']);

searchApp.controller('SearchCtrl', function ($scope, $http) {
  $http.get('search-json').success(function(json) {
    $scope.item = json.data;
    $scope.orderProp = 'title';
  });
});

谢谢

【问题讨论】:

  • 如果 json.data 是一个对象数组,你必须编写 {{item[0].title}} 或使用 ng-repeat
  • 这就是我所做的,问题是 item.description 以

    Some HTML

    而不是 html
    的形式出现

标签: angularjs ng-bind-html


【解决方案1】:

添加 ngSanitize ,注入 $sce 然后在 js 中

   $scope.getHtml = function(html) {
       return $sce.trustAsHtml(html)    
   }

在html中

<span>{{item.title}}</span>
<div data-ng-bind-html="getHtml(item.description)"> <div>

【讨论】:

  • 谢谢,这似乎可行,但我认为对于 1.3 版,您不再需要 getHtml。只需添加 $sce 似乎就可以解决我的问题。不知道为什么
猜你喜欢
  • 1970-01-01
  • 2021-09-12
  • 1970-01-01
  • 2014-04-07
  • 2019-06-11
  • 2018-06-12
  • 2021-02-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多