accordion with ng-repeat and ng-bind-html won't work

JackTurky picture JackTurky · Jan 30, 2014 · Viewed 12.3k times · Source

I'm trying to use accordion and html content in this way:

<accordion>
   <accordion-group ng-repeat="item in items">
      <accordion-heading>
          <a class="btn btn-primary btn-block btn-elenco">
         <img postsrc="img/flag/flag_{{item.index}}.jpg">
      </a>
      </accordion-heading>
      <p ng-bind-html="item.content"></p>
   </accordion-group>
</accordion>

AND

var items = [];
for(var i=0;i<10;i++){
var content = "<div>TEST</div>";
items.push({index:i,content:content});
}
$scope.items = items;

var app = angular.module('MyApp',['ngSanitize','ui.bootstrap']);

Accordion works but html isn't rendered into p tag.

What could be the problem?

EDIT

If i try something like:

<div ng-bind-html="to_trusted(item.content)"></div>

And add function to controller:

$scope.to_trusted = function(html_code)
    {
    console.log(html_code);
    return $sce.trustAsHtml(html_code);
    }

Nothing changes and in console i get many "undefined"!

Answer

Marco van Dijk picture Marco van Dijk · Jan 30, 2014

This is because the HTML content is declared unsafe by Angular due to it's Strict Contextual Escaping.

Another SO answer already explains clearly how this can be solved: HTML injection, that is if you are using Angular version 1.2.0 or up.

I created a Plunkr to match your case.