【问题标题】:Angular bind html from Html entities来自 Html 实体的 Angular 绑定 html
【发布时间】:2017-07-20 10:01:04
【问题描述】:

如何编码 HTML 实体并显示 HTML ?我在这张票上附上了样本小提琴

控制器:-

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 的段落有很多变体,但大多数都受到了某种形式的改变,通过注入幽默或随机词,看起来甚至有点不可信。

房间

示例 Js 小提琴:- http://jsfiddle.net/68n89rj3/

【问题讨论】:

  • 为什么不能使用&lt;&gt;' rather than '&amp;lt;' and >`?
  • @TejinderSingh 实际上数据来自后端

标签: angularjs ng-bind-html ng-bind


【解决方案1】:

它不起作用,因为您的 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();

这有点小技巧,你首先创建一个无父元素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>

【讨论】:

  • 一切正常。 HTML文件本身是否有其他解决方案?
  • 并非如此。但是你可以编写一个过滤器来为你做这件事,尽管这样每次元素被角度重新编译时它都会被重新解码。我已经包含了这样一个过滤器,尽管我仍然建议您在控制器中只解码一次。
猜你喜欢
  • 1970-01-01
  • 2019-05-06
  • 2020-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-11
  • 1970-01-01
  • 2017-09-20
相关资源
最近更新 更多