Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Insert HTML from a string

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.

  • AngularJS : Insert HTML into view
  • AngularJS $http HTML Parser
  • angularjs - inserting $compile-d html
  • AngularJS doesn't execute in HTML inserted with document.write()
  • Escape HTML text in an AngularJS directive
like image 835
Sir Robert Avatar asked Feb 07 '13 21:02

Sir Robert


People also ask

What is Ng-bind-HTML in AngularJS?

The ng-bind-html directive is a secure way of binding content to an HTML element. When you are letting AngularJS write HTML in your application, you should check the HTML for dangerous code. By including the "angular-sanitize.

Can we use HTML in angular?

In Angular templates, you can use plain HTML but also special syntax and directives that allow you to take benefits of the full power of Angular features such as interpolation, binding, ngClass, ngStyle, ngFor and ngIf, etc.

What is the output of this AngularJS expression?

Expressions behave similar to ngbind directives. AngularJS expressions are pure JavaScript expressions and output the data where they are used.


1 Answers

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> 
like image 68
ganaraj Avatar answered Oct 11 '22 21:10

ganaraj