0

I get JSON like this

{
 "lots of":"keys"
 "description" : {
   "key":"Some sample key",
   "value":"This is the markup™"
  }
}

from server and I ultimately iterate the description objects and populate table rows with two columns: one for the key and one for the value.

I have tried putting on my <td> tag ng-bind-html as well as injecting $sce into my controller and using trustAsHtml but so far the string always displays as it is in the JSON. Not every value will be HTML but I can easily detect based on the key if HTML is a possibility. It seemed when I put in the directive on the td it did not display anything if no HTML was present. I am interested in using something that can allow HTML in the value but not require it so I can display either

HTML fragment

  <tr ng-repeat="(key, val) in record.description">
                        <td>{{key}}:</td>
                        <td>{{val}}</td>
   </tr>
Barry
  • 1,800
  • 2
  • 25
  • 46

2 Answers2

1

Angular was designed with security in mind, and will prevent you from displaying HTML from raw strings whenever possible - to prevent various injection attacks.

Here is workarround for your problem: AngularJS: Insert HTML from a string. Generally you should use ng-bind-html insted of ng-bind (this is used by curly braces).

Community
  • 1
  • 1
csharpfolk
  • 4,124
  • 25
  • 31
1

I created a quick fiddle here: https://jsfiddle.net/frishi/mvw97s3q/6/

I used angular-sanitize, which I am not sure you mentioned injecting in your module dependency list. Either way, the example works simply by using ng-bind-html

Relevant docs page: https://docs.angularjs.org/api/ng/directive/ngBindHtml

It works by using the directive ng-bind-html on the element you want to display the HTML string in. You use it like so:

<p ng-bind-html="data.firstName"></p>

assuming that data.firstName = "<strong>FeeFee</strong>" or something like that.

I would also like to add that Angular does not allow this natively because of legitimate security concerns. That and the fact that allowing arbitrary HTML to be rendered might not always produce desirable results. Your page layout could quite possibly break because of some HTML you allowed to be passed through.

frishi
  • 862
  • 1
  • 10
  • 27
  • selected this answer because of the fiddle since ```ng-bind-html``` wasn't working without including ngSanitize in the module ( I had over looked this) – Barry Jan 20 '16 at 21:55