1

I am trying to create an html elemnt from string in js.

The string is: "<p class='text-muted'> come and see how good I look </p>".

In the past I did this with php by echo it out and now I build the client side only with angularJS and I have no clue how to do it.

I tried to bind the string to the page but, as expected, it prints the whole string without encode the string to html elemnt..

I tried to look for an answer in the internet and specificly in this community without succuess..

Does it possible, and if so, How?

Thanks in advance

epascarello
  • 204,599
  • 20
  • 195
  • 236
Ori
  • 82
  • 1
  • 8
  • 1
    Do you want it in JavaScript or Angular? Show some context on how you are using it since there are multiple ways to do it. – epascarello Aug 11 '17 at 16:59

2 Answers2

1

You can use the ng-bind-html directive to bind a string of html to an element. The string should be sanitised first for example by injecting $sceand calling $sce.trustAsHtml() on the string to bind.

Example controller:

app.controller('MainCtrl', function($scope, $sce) {
  $scope.template = $sce.trustAsHtml('<p class="text-muted"> come and see how good I look </p>');
});

And in html

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

Here's a quick example plunker You can type in html and click to bind it

Tim Andrews
  • 827
  • 1
  • 7
  • 21
0

You can attach a String definition of html to any DOM Elment using the property 'innerHTML'.

yourDomEl.innerHTML = '<div class="your-class"><a>Link</a></div>';