Why is ng-bind-html not displaying anything?

做~自己de王妃 提交于 2019-12-04 11:17:50

问题


I am displaying a string that has HTML code in it:

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

put it displays the HTML code instead of interpreting the elements:

When I use ng-bind and ng-bind-unsafe, it shows nothing.

How can I get the HTML to be parsed?

Addendum

I added a reference to sanitize but ng-bind and ng-bind-unsafe still show nothing:

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

Ok, I added the ngSanitize var app = angular.module('app', ['ngSanitize']); and now it works.


回答1:


It looks like you missed ngSanitize please see demo below

You can find more here

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>



回答2:


call apply

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


来源:https://stackoverflow.com/questions/27880658/why-is-ng-bind-html-not-displaying-anything

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!