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

1
  • 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. Commented Aug 11, 2017 at 16:59

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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>';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.