4

I have a variable in a scope with some HTML content. I want to render it as HTML on the webpage, but in my case it displays as full text. Can anyone help me?

This is my code:-

//contoller.js

$scope.message = '<b><i>result has been saved successfully.</i></b>';

//demo.html

<p ng-bind="message"></p>
6
  • 2
    Why do you need html string in controller and not template this? Commented Mar 3, 2016 at 13:07
  • because i wanted to display a successfull message while user click on Save Button and i want that message look good. Commented Mar 3, 2016 at 13:14
  • So make it look good in the template and pass in text...that is the normal approach. Commented Mar 3, 2016 at 13:17
  • don't i use in controller. If i want? Commented Mar 3, 2016 at 13:19
  • Makes no sense doing it in controller. no separation of concerns and requires more complicated process to inject it. That's what templates are for Commented Mar 3, 2016 at 13:20

3 Answers 3

14

You need to inject $sce service into your controller or Directive etc. and use $sce service like this:-

$scope.Message = $sce.trustAsHtml("<b><i>result has been saved successfully.</i></b>");

And bind this in your HTML page e.g;

<p ng-bind-html = "Message"></p>
Sign up to request clarification or add additional context in comments.

Comments

3

You have to secure your content with the $sce service and then use the

ng-bind-html directive

docs here.


EDIT

you can find the usage of sce.trustAsHtml here.

1 Comment

You're welcome! Hope you'll enjoy your angular experience!
1
<p ng-bind-html="message"></p>

1 Comment

ng-bind-html what more explanation is needed? this should solve the problem

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.