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

1

2 Answers 2

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/

Sign up to request clarification or add additional context in comments.

2 Comments

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?
This is by far the better answer. Thank you so much.
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.

1 Comment

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 &lt;) in the js function

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.