Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Is it possible to create an HTML fragment in an Angular controller and have this HTML shown in the view?

This comes from a requirement to turn an inconsistent JSON blob into a nested list of id : value pairs. Therefore the HTML is created in the controller and I am now looking to display it.

I have created a model property, but cannot render this in the view without it just printing the HTML.


Update

It appears that the problem arises from angular rendering the created HTML as a string within quotes. Will attempt to find a way around this.

Example controller :

var SomeController = function () {

    this.customHtml = '<ul><li>render me please</li></ul>';
}

Example view :

<div ng:bind="customHtml"></div>

Gives :

<div>
    "<ul><li>render me please</li></ul>"
</div>
share|improve this question
Also please see this question, asking if it's possible to get scripts in inserted HTML to run. – enigment Dec 4 '12 at 22:19

2 Answers

up vote 78 down vote accepted

Swaff's answer was correct as of that date but that doesn't work anymore; now you use:

UPDATE: as Damax pointed out, now use:

<div ng-bind-html-unsafe="expression"></div>

OLD WAY:

<div ng-bind-html="expression"></div>

instead of

<div>{{expression}}</div>

https://github.com/angular/angular.js/blob/master/CHANGELOG.md (scroll down / search for "ng-bind-html" in this page to see details of the change)

ALSO, this now requires the "ngSanitize" module (I got hung up on this for awhile and couldn't figure out why it wasn't working - and the documentation doesn't seem clear on how to include this module). There's 2 steps:

  1. include the angular-sanitize.min.js resource, i.e.:
    <script src="lib/angular/angular-sanitize.min.js"></script>

  2. In a js file (controller or usually app.js), include ngSanitize, i.e.:
    angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'ngSanitize'])

share|improve this answer
1  
Thanks for posting this. It helped me very much. – fatmatto Jul 9 '12 at 13:44
Answer is in need of revision again (see Damax's answer). – Langdon Mar 22 at 18:07

I have tried today, the only way I found was this

<div ng-bind-html-unsafe="expression"></div>

share|improve this answer
4  
This solution should be used only if the source is trustful to avoid cross-site scripting attacks. – Bertrand Oct 4 '12 at 18:39
3  
I found this was the only thing that worked for me. – Michael Dausmann Oct 13 '12 at 4:59
1  
As of Angular 1.0.2, this works for me, with no other files or hookup required. – enigment Dec 4 '12 at 20:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.