LT86
LT86

Reputation: 655

Angular JS - How can I sanitize HTML in a controller?

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))} 

Upvotes: 3

Views: 4826

Answers (3)

Wtower
Wtower

Reputation: 19912

$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.

Upvotes: 2

acg
acg

Reputation: 961

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))

Upvotes: 0

Zafta
Zafta

Reputation: 667

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)

Upvotes: 1

Related Questions