75

I've looked a LOT for this, but I either I can't find the answer or I don't understand it. A specific example will win the vote =)

  • I have a function that returns an HTML string.
  • I can't change the function.
  • I want the html represented by the string to be inserted into the DOM.
  • I'm happy to use a controller, directive, service, or anything else that works (and is reasonably good practice).
  • Disclaimer: I don't understand $compile well.

Here's what I've tried:

// My magic HTML string function.
function htmlString (str) {
    return "<h1>" + str + "</h1>";
}

function Ctrl ($scope, $compile) {
  $scope.htmlString = htmlString;
}
Ctrl.$inject = ["$scope", "$compile"];

That didn't work.

I tried it as a directive too:

// My magic HTML string function.
function htmlString (str) {
    return "<h1>" + str + "</h1>";
}

angular.module("myApp.directives", [])
  .directive("htmlString", function () {
    return {
      restrict: "E",
      scope: { content: "@" },
      template: "{{ htmlStr(content) }}"
    }
  });

  ... and in my HTML ...

  <html-string content="foo"></html-string>

Help?

Note

I looked at these, among others, but couldn't make it work.

Community
  • 1
  • 1
Sir Robert
  • 4,686
  • 7
  • 41
  • 57

2 Answers2

93

Have a look at the example in this link :

http://docs.angularjs.org/api/ngSanitize.$sanitize

Basically, angular has a directive to insert html into pages. In your case you can insert the html using the ng-bind-html directive like so :

If you already have done all this :

// My magic HTML string function.
function htmlString (str) {
    return "<h1>" + str + "</h1>";
}

function Ctrl ($scope) {
  var str = "HELLO!";
  $scope.htmlString = htmlString(str);
}
Ctrl.$inject = ["$scope"];

Then in your html within the scope of that controller, you could

<div ng-bind-html="htmlString"></div>
Blake
  • 1,691
  • 2
  • 15
  • 23
ganaraj
  • 26,841
  • 6
  • 63
  • 59
  • 1
    Thanks! That worked. Made some edits: Fixed the link (SO parsed it weirdly), changed "ng-bind-html" to "ng-bind-html-unsafe", and gave a more full example. – Sir Robert Feb 11 '13 at 17:35
  • 8
    It's `ng-bind-html-unsafe` up until 1.0.8, after that it's just `ng-bind-html` because the safe and unsafe functions were merged https://github.com/angular/angular.js/blob/master/CHANGELOG.md#120-rc1-spooky-giraffe-2013-08-13 – Matt Sep 23 '13 at 16:12
  • 9
    @AakilFernandes, I had to add ```ngSanitize``` to my main module for ```ng-bind-html``` to work. – igreulich Mar 02 '15 at 21:02
15

you can also use $sce.trustAsHtml('"<h1>" + str + "</h1>"'),if you want to know more detail, please refer to $sce

Python Basketball
  • 2,320
  • 3
  • 24
  • 47