Friday, October 16, 2015

Angular Recipe: Insert html string from js into html (solve Error: [$sce:unsafe])

Angular JS


Insert html string from js into html

If u'll try to insert the string with html tags as it

<div "<p>Some Cool Text</p>"</div>

U'll see just a string with it's tags instead of html

<p>Some Cool Text</p>

To insert it like html u've to use ng-bind-html directive @see Angular API - NgBind

<div ng-bind-html="'<p>Some Cool Text</p>'"></div>   

However to avoid security vulnerabilities it's avoided to insert html, so u'll receive the following error:

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


Get ng-bind-html working

To resolve this problem you have to use '$sce' @see Angular API - Strict Contextual Escaping

.html

<div ng-bind-html="getHTMLString()"></div>  

.js

$scope.getHTMLString = function(){
    return $sce.trustAsHtml("<p>Some Cool Text</p>");
};

Well Done (output):

Some Cool Text

Be aware: Generated html string with some ng-directive tags inside (e.g. ng-src) won't work if you will try to insert it via ng-bind-html :(


see Also


3 comments:

  1. The official source for NFL news, video highlights, fantasy football, game-day coverage, schedules, stats, scores and more. Patriots Football

    ReplyDelete
  2. With havin so much written content do you ever run into any problems of plagorism or copyright violation? My blog has a lot of exclusive content I've either written myself or outsourced but it appears a lot of it is popping it up all over the web without my agreement. Do you know any solutions to help reduce content from being ripped off? I'd definitely appreciate it.

    ReplyDelete
  3. Great content with proper explanation. I've some doubts but now all is clear. Thanks for explaining it perfectly.

    Vision11 is played by using your sport knowledge and skill. You can pick your own team made up of real players for Cricket, Football, NBA. Create your team within a maximum budget of 100 credits.

    fantasy sports website

    ReplyDelete