8

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?

2 Answers 2

18

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',
Sign up to request clarification or add additional context in comments.

1 Comment

This answer should definitely receive more upvotes since it is way lighter in terms of runtime overhead and code necessary for the implementation (although unicode character numbers might not be as comprehensible at first sight...).
11

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/

1 Comment

Thanks, I have been pulling out my hair! Note to those who follow: it seems to work only with ng-bind-html, not {{ }} binding

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.