T J
T J

Reputation: 43166

How to display HTML character Entities in CSS pseudo elements with angularjs

I'm trying to output HTML character Entities as data attributes so that I can display it as I wish using css pseudo elements.

This works when we directly assign the value of attribute in HTML, but doesn't when we bind the value using angular.

Below is the sample code:

var app = angular.module('test', []);
app.config(function($sceProvider) {
  // Completely disable SCE.  For demonstration purposes only!
  // Do not use in new projects.
  $sceProvider.enabled(false);
});
app.controller('testCtrl', ['$scope',
  function($scope) {
    $scope.symbol = "\00a9";
    $scope.symbol1 = "©";
  }
])
.copy::before {
  content: attr(data-symbol);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test" ng-controller="testCtrl">
  <div class="copy" data-symbol="&copy;">working</div>

  <div class="copy" data-symbol="{{symbol}}">not working</div>
  <div class="copy" data-symbol="{{symbol1}}">also not working</div>
</div>

As you can see, I tried disabling $sce entirely as well (for testing purpose). But that also didn't work.

There will be way too many of these symbols in the application so generating a DOM element for each of them doesn't seem like a good idea.

Is there a way to do this..?

Upvotes: 3

Views: 916

Answers (1)

GOTO 0
GOTO 0

Reputation: 47851

Part of the problem is that AngularJS automatically escapes character sequences to be rendered in HTML. So for instance the character "&" in the string "&copy;" is escaped as "&amp;", thus producing the text "&amp;copy;" which renders in HTML as "&copy;" rather than the desired "©".

Long story short, to render a particular character from an angular file, we don't use HTML entities, but simply the characters themselves. In this case, having the character "©" in a JavaScript file is perfectly valid as long as UTF-8 encoding is used. So we can rewrite the culprit line as

$scope.symbol = "©";

If it's necessary to use only ASCII characters, we use JavaScript escape sequences for the purpose, such as

$scope.symbol = "\u00a9";

The 4 characters after the "\u" part are the hexadecimal representation of the Unicode character code, here 169 for the copyright sign. A search is available here: http://www.fileformat.info/info/unicode/char/search.htm

Another way to get the same sequence in JavaScript if we have the character would be:

"©".charCodeAt(0).toString(16)

And left padding the result with zeros.

Upvotes: 4

Related Questions