3

I'm trying to sanitize HTML in the controller as I'm trying to update the document.title dynamically with the title of the post. (I know that for SEO purposes this isn't recommended but I need to use it here)

$scope.prevTitle = "dynamic title gets pulled in here &"
document.title = $scope.prevTitle 

For this example, I've just used a random HTML entity. I've tried the parseAsHtml method from the official documentation but I'm having no luck. I tried the following:

document.title = $sce.parseAsHtml($scope.prevTitle)

But no luck. The documentation suggests it needs to be used within a function. Any suggestions on how I would acheive this?

A console log of the above ( console.log($sce.parseAsHtml($scope.prevTitle)) ) would return:

function (b,c){return e.getTrusted(a,d(b,c))} 
LT86
  • 635
  • 2
  • 15
  • 29
  • 1
    I think the problem here is that you can't put HTML into a `document.title`, you'll need to [HTML decode it](http://stackoverflow.com/questions/5796718/html-entity-decode) – CodingIntrigue Aug 28 '14 at 12:15

3 Answers3

2

$sanitize can be used as @acg pointed out. Alternatively, you can use it directly with the ng-bind-html directive where it automatically sanitizes the output variable before rendering the output.

The above point is not quite clear in the documentation, but there is a fairly extensive example in it with which you can play in pluncker.

Please also bear in mind that ngSanitize is an external module and you need to explicitly load angular-sanitize.js or include it in your js minification.

Wtower
  • 18,848
  • 11
  • 103
  • 80
1

Use $sanitise and trustAsHtml instead

First of all inject 'ngSanitize' in your module

Now in your controller, just add

$scope.prevTitle = "dynamic title gets pulled in here &"
document.title = $sce.trustAsHtml($scope.prevTitle)
Zafta
  • 655
  • 1
  • 10
  • 26
  • 1
    Thanks but this appears to do the opposite or just have no effect at all? I've injected ngSanitize in my module a while ago. – LT86 Aug 28 '14 at 12:45
  • You do not need `$sce.trustAsHtml` for `ngSanitize` to work. On the contrary, this allows a non-escaped HTML string to be displayed. – Wtower Jul 21 '16 at 17:36
0

If you want to sanitize the html returned, I would think it would be as simple as using the $sanitize service:

document.title = $sanitize($sce.parseAsHtml($scope.prevTitle))
acg
  • 961
  • 5
  • 10
  • 1
    Thanks for the answer. Unfortunately this just prevents the title from updating at all. Console gives me $sanitize is not defined even though I've defined it as a dependency – LT86 Aug 28 '14 at 12:42
  • @LT86 have you included the `angular-sanitize.js` file? @acg, why would you need to `parseAsHtml` before sanitizing? – Wtower Jul 21 '16 at 17:53