Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render html formatted content in ng-grid?

I have jsonData which consist of HTML content. I want to render that HTML in ng-grid. The content is not rendered however -- it only shows up in normal string format.

Below is the plnkr which shows all the code:

http://plnkr.co/edit/RlWyDqCUUR15dmLM7ePV?p=preview

like image 715
Mayur Avatar asked Jan 09 '23 15:01

Mayur


1 Answers

There's a few things going on here:

  1. Not related to your exact issue, but you've got nested single quotes in your firstName field. You need to do some escaping or your ng-click expression is going to break. So instead of ng-click='show('F:/cox/main.html')' you can do ng-click=\"show('F:/cox/main.html')\".
  2. Also not related to your exact issue, but if you want to access properties on your controller's scope from inside UI-Grid you need to use appScope. The docs on it are here: http://ui-grid.info/docs/#/tutorial/305_appScope
  3. The main problem with getting HTML provided from inside your app to render is Strict Contextual Escaping.

Strict Contextual Escaping (SCE) is enabled by default in Angular and escapes any arbitrary HTML to prevent things like XSS and clickjacking. In order to get your HTML to show up you need to trust it, and bind it with an HTML bind expression.

You can use the $sce service to trust the HTML. Just iterate over your rows and do $sce.trustAsHtml(row.firstName). (You can read more about SCE here: https://docs.angularjs.org/api/ng/service/$sce) Then you will need a custom cell template to bind the HTML. The simplest one looks like this:

<div class="ui-grid-cell-contents" ng-bind-html="COL_FIELD"></div>

COL_FIELD will get transformed by UI-Grid into the proper binding for your field. Now the problem is that your ng-click directive doesn't get compiled. You need to use a directive that will take your custom HTML and compile it. You could roll your own, or use something like this library to do it for you: https://github.com/incuna/angular-bind-html-compile

The main thing to keep in mind is being able to actually trust the source of your HTML. If you can't be sure then going about this another way (i.e. by not providing HTML inside your data set) would be better.

I've modified your plunker to show all this working together: http://plnkr.co/edit/MgLoeGBoRTi2fF3e6pia?p=preview

like image 137
c0bra Avatar answered Jan 28 '23 00:01

c0bra