Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display Unicode in HTML with AngularJS?

I am having a problem displaying Unicode in HTML from an AngularJS controller. Here is my 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'
        }
    ];
});

And here is my 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>

I tried $sanitise() and trustAsHtml but without success. So, how can I display the Unicode Downwards Arrow in my HTML?

like image 380
jeewan Avatar asked Apr 22 '14 21:04

jeewan


People also ask

How do I show Unicode in HTML?

You can enter any Unicode character in an HTML file by taking its decimal numeric character reference and adding an ampersand and a hash at the front and a semi-colon at the end, for example &#8212; should display as an em dash (—). This is the method used in the Unicode test pages.

Is HTML in Unicode?

The Unicode Standard has become a success and is implemented in HTML, XML, Java, JavaScript, E-mail, ASP, PHP, etc. The Unicode standard is also supported in many operating systems and all modern browsers.


2 Answers

Avoid writing HTML markup from script. As soon as the data may content HTML-special characters like < and & you've got breakage and potentially security issues (XSS).

The character referred to by the HTML markup &darr; is U+2193 Downwards Arrow. You can refer to it directly in JavaScript using a JS string literal escape:

'name': '\u2193NASDAQ',

Or if your page/script is consistently saved and served in a Unicode-safe format (eg UTF-8) then you don't need to escape it at all:

'name': '↓NASDAQ',
like image 95
bobince Avatar answered Oct 12 '22 23:10

bobince


Angular ships with Strict Contextual Escaping. So you'd have to explicitly say that you want to render some character as HTML.

Notice, I have also added ng-sanitize in the External Resources.

I created a new filter

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

and used it in view like this:

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

http://jsfiddle.net/9UdVY/

like image 39
javaCity Avatar answered Oct 13 '22 01:10

javaCity