7

I'm trying to display a string in my model that contains the html representation of a special character. Unfortunately, it doesn't show that actual character, and I don't know how to make it do it...

this is the code:

<div ng-controller="MyCtrl">
  Hello, {{namea}}!
    <br/>
    &lt;
</div>

<script>
var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.namea = 'Superhero &lt;';
}
</script>

this is the output:

Hello, Superhero &lt;! 
<

here is a jsfiddle for that

Moshe Shaham
  • 15,448
  • 22
  • 74
  • 114
  • possible duplicate of [parse html inside ng-bind using angularJS](http://stackoverflow.com/questions/14888822/parse-html-inside-ng-bind-using-angularjs) – Stewie Jun 22 '13 at 14:45

2 Answers2

19

I ran into this problem today. Using AngularJS, in data inside a controller, I was trying to include a string with 'n' with tilde. I tried "Español" as well as the html representation, and neither displayed the desired output.

A coworker helpfully pointed out that unicode works. So I tried

{
name : "my site en Espan\u00F1ol"
}

which gave me

my site en Español

as desired. Check out http://unicode-table.com/en/

Lindsey
  • 191
  • 2
  • 3
  • 3
    I'm new to angular, but what I don't get is that if it's on a page that's already in utf8 encoding, why is the html encoding even happening? ñ is a legal character in that environment and even latin 1; it's not an html syntax character like &, <, or >. It's not even "dicey" like ' or ". So why is angular mucking with it and is there a way to make it stop? – user1664043 Oct 02 '15 at 20:03
  • This is by far the better answer. Thank you so much. – forgivenson Jul 21 '16 at 00:35
7

You can use ng-bind-html-unsafe directive:

<div ng-controller="MyCtrl" ng-bind-html-unsafe="'Hello,' + namea">
</div>

Check out the examples in the docs and the jsfiddle.

Elias Dorneles
  • 22,556
  • 11
  • 85
  • 107
  • 5
    With newer version of angular, ng-bind-html-unsafe doesn't exists anymore. You will need to use ng-bind-html in your html template and $sce.trustAsHtml('Superhero <) in the js function – Julien Boulay Mar 14 '14 at 13:02