为什么ng-bind-html没有显示任何内容?

时间:2015-01-10 20:04:39

标签: angularjs ng-bind-html

我正在显示一个包含HTML代码的字符串:

<div style="font-size: 14px" ng-bind="currentBook.description"></div>

让它显示HTML代码而不是解释元素:

enter image description here

当我使用ng-bindng-bind-unsafe时,它什么都没有显示。

如何解析HTML?

附录

我添加了对清理的引用,但ng-bindng-bind-unsafe仍未显示任何内容:

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-route.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-sanitize.js"></script>

好的,我添加了ngSanitize var app = angular.module('app', ['ngSanitize']);,现在可以了。

2 个答案:

答案 0 :(得分:12)

看起来您错过了 ngSanitize ,请参阅下面的演示

你可以在这里找到更多

https://docs.angularjs.org/api/ngSanitize/service/ $ sanitize方法

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

app.controller('firstCtrl', function($scope, $sce) {
  $scope.currentBook = {
    description: "<p>some description</p>"

  };
});
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-sanitize.js"></script>

<body ng-app="app">
  <div ng-controller="firstCtrl">
    <div style="font-size: 14px" ng-bind-html="currentBook.description"></div>
  </div>
</body>

答案 1 :(得分:3)

致电申请

    $scope.$apply(function () {
            $scope.currentBook.description = $sce.trustAsHtml(html);
        });