在Angular JS中解码HTML实体

krs*_*785 25 html javascript html-entities utf8-decode angularjs

如何使用angular JS在文本中解码HTML实体.

我有字符串

""12.10 On-Going Submission of ""Made Up"" Samples.""
Run Code Online (Sandbox Code Playgroud)

我需要一种使用Angular JS解码的方法.我在这里找到了一种使用javascript的方法,但我相信它不适用于Angular.需要在UI上找回原始字符串,看起来像

""12.10 On-Going Submission of ""Made Up"" Samples.""
Run Code Online (Sandbox Code Playgroud)

rye*_*lar 43

您可以使用该ng-bind-html指令将其显示为html内容,并解码所有html实体.只需确保ngSanitize在您的应用程序中包含依赖项.

DEMO

JAVASCRIPT

angular.module('app', ['ngSanitize'])

  .controller('Ctrl', function($scope) {
    $scope.html = '"12.10 On-Going Submission of ""Made Up"" Samples."';
  });
Run Code Online (Sandbox Code Playgroud)

HTML

  <body ng-controller="Ctrl">
    <div ng-bind-html="html"></div>
  </body>
Run Code Online (Sandbox Code Playgroud)

  • 但如果你不习惯将其渲染成html,你怎么能处理它呢? (18认同)

Fra*_*jak 22

如果您不想使用ngSanitize,可以这样做:

在你的控制器中:

$scope.html = '&quot;12.10 On-Going Submission of &quot;&quot;Made Up&quot;&quot; Samples.&quot;'
$scope.renderHTML = function(html_code)
        {
            var decoded = angular.element('<textarea />').html(html_code).text();
            return $sce.trustAsHtml(decoded);
        };
Run Code Online (Sandbox Code Playgroud)

在模板中:

<div ng-bind-html="renderHTML(html)"></div>
Run Code Online (Sandbox Code Playgroud)

只需确保在控制器中注入$ sce