userimage

AngularJS : Insert HTML into view

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>

userimage

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

For Angular 1.3, use ng-bind-html in the HTML:

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

and use $sce.trustAsHtml() in the controller to convert the html string.

 $scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml(someHtmlVar);

UPDATE 2: as Sasha points out, for Angular 1.2, use:

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

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:

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

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

Answer is