Angular 从 Html 个实体绑定 html

Angular bind html from Html entities

如何编码 HTML 实体并显示 HTML ?我在这张票

上附上了样本 fiddle

控制器:-

angular.module('myapp', ['ngSanitize'])
.controller('foo', function($scope) {
    $scope.bar = "<p><b>Lorem Ipsum</b> <br />There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour.or randomised words which don't look even slightly believable.</p><p><b>Rooms</b> <br /&gt";
});

angular.bootstrap(document, ['myapp']);

HTML :-

<div ng-controller="foo">

    <div ng-bind-html="bar"></div>

</div>

输出:-

<p><b>Lorem Ipsum</b> <br />There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour.or randomised words which don't look even slightly believable.</p><p><b>Rooms</b> <br /> 

预期输出:-

Lorem Ipsum

Lorem Ipsum 的段落有很多变体,但大多数都以某种形式发生了变化,注入了 humour.or 随机单词,这些单词看起来甚至都不可信。

房间

示例 Js fiddle :- http://jsfiddle.net/68n89rj3/

它不起作用,因为您的 HTML 已经编码,所以它只输出编码的 html 字符。您需要先解码 HTML,然后再将其分配给 $scope.bar 变量。

一种方法是这样的:

$scope.bar = angular.element('<div>').html("&lt;p&gt;&lt;b&gt;Lorem Ipsum&lt;/b&gt; &lt;br /&gt;There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour.or randomised words which don't look even slightly believable.&lt;/p&gt;&lt;p&gt;&lt;b&gt;Rooms&lt;/b&gt; &lt;br /&gt").text();

这有点 hack,首先创建一个无父元素的 div 元素(因此它只存在于内存中),将字符串添加为该元素的 html,最后提取文本。那应该适合你。


添加过滤器来完成:

angular.module('app').filter('htmldecode', function(){
    return function(encodedHtml) {
        return angular.element('<div>').html(encodedHtml).text();
    };
});

并像这样使用它:

<div ng-bind-html="bar | htmldecode"></div>