How to securely receive and set text from external source in angularjs app

4.40K viewsProgrammingangularjs javascript programming

I am receiving some text from a web service which has html tags and I want to render the text as html. How can this be done ?

Answered question

You can use angularjs $sce (strict contextual escaping) to make angular render the text as html. You need to pass an instance of $sce along with $scope in your controller.
Say for eg, if your model name is person and it holds the text that you receiving from web service.
You need the following:-
In your markup, do the following

<p ng-bind-html="getHtml(person)">{{person}}</p>

Then in your angular app.js which has the controller for this, add the below code

$scope.getHtml = function(html){
    return $sce.trustAsHtml(html);
 app.filter('html', function($sce) {
    return function(val) {
        return $sce.trustAsHtml(val);

where app is the angular app instance. This should be good to get rid of the

[$sce:unsafe] Attempting to use an unsafe value in a safe context.

Answered question
Write your answer.