使用AngularJS在HTML中显示Unicode

Display Unicode in HTML with AngularJS?

本文关键字:显示 Unicode HTML AngularJS 使用      更新时间:2023-09-26

我在AngularJS控制器的HTML中显示Unicode时遇到问题。这是我的JavaScript:

var mOverview = angular.module('mOverview', []);
mOverview.controller('mOverviewController', function ($scope, $sce) {
  $scope.mData = [
    {
        'name': '↓'+'NASDAQ', // here the unicode is ↓ but the output is also ↓ which is supposed to be a down-arrow
        'amount': '15,698.85',
        'upDown': '+105.84'
        }
    ];
});

这是我的HTML:

<div ng-app="mOverview">
  <div ng-controller="mOverviewController">
    <table>
      <tr>
        <th></th>
        <th></th>
        <th></th>
      </tr>
      <tr ng-repeat="md in mData">
        <td>{{md.name}}</td>
        <td>{{md.amount}}</td>
        <td>{{md.upDown}}</td>
      </tr>
    </table>
 </div>

我尝试了$sanitise()trustAsHtml,但没有成功。那么,如何在HTML中显示Unicode向下箭头呢?

避免从脚本中编写HTML标记。一旦数据可能包含像<&这样的HTML特殊字符,就会出现损坏和潜在的安全问题(XSS)。

HTML标记&darr;所引用的字符是U+2193向下箭头。您可以使用JS字符串文字转义符在JavaScript中直接引用它:

'name': ''u2193NASDAQ',

或者,如果您的页面/脚本始终以Unicode安全格式(例如UTF-8)保存和提供,那么您根本不需要对其进行转义:

'name': '↓NASDAQ',

具有严格上下文转义的角度船舶。因此,您必须明确表示要将某些字符呈现为HTML。

注意,我还在外部资源中添加了ng-sanitize

我创建了一个新的过滤器

mOverview.filter('unsafe', function($sce) {
    return function(val) {
        return $sce.trustAsHtml(val);
    };
});

并在这样的视图中使用它:

<td ng-bind-html="md.name | unsafe"></td>

http://jsfiddle.net/9UdVY/