user815437
user815437

Reputation:

Unable to display safe html in Angular UI-Grid

I'm trying to display html in UI-Grid that is sent from the server. An example is my column header containing a tooltip's HTML that was created server side and concatenated to the string (for some reason). I need that to display as HTML but regardless of SCE setting, it still displays the HTML encoded. Here is an example that replicates my issue:

var app = angular.module('app', ['ngTouch', 'ui.grid']);

app.config(function($sceProvider){
    $sceProvider.enabled(false); 
}); 

app.controller('MainCtrl', ['$scope', function ($scope) {
  $scope.gridOptions = {
    columnDefs: [
      { 
        displayName: "First Name",
        field: "firstName",
        cellFilter: "exampleFilter:this"
      },
      {
        displayName: "First Name",
        field: "lastName",
      },
      {
        displayName: "First Name",
        field: "company",
      },
      {
        displayName: "First Name",
        field: "employed",
      }
    ]
  }; 

  $scope.gridOptions.data = [
    {
        "firstName": "Cox",
        "lastName": "Carney",
        "company": "Enormo",
        "employed": true 
    },
    {
        "firstName": "Lorraine",
        "lastName": "Wise",
        "company": "<span>Comveyer</span>",
        "employed": false
    },
    {
        "firstName": "Nancy",
        "lastName": "Waters",
        "company": "Fuelton",
        "employed": false
    }
];
}]);
app.filter('exampleFilter', function ($sce) {
  console.log($sce.isEnabled());
  return function (value) {
    return $sce.trustAsHtml("<span>Here</span>");
        //return (isNaN(parseFloat(value)) ? '0.0' : Number(value).toFixed(2)) + "%";
  }
}); 

This is my plunker demo

Upvotes: 3

Views: 2500

Answers (2)

Bruno Lemos
Bruno Lemos

Reputation: 9263

If you want to render the html of a filtered field, you can do this:

cellTemplate: '<div class="ui-grid-cell-contents" ng-bind-html="grid.getCellDisplayValue(row ,col)"></div>'

You may need to install ngSanitize plugin to ng-bind-html work.

Upvotes: 2

bumpy
bumpy

Reputation: 2002

You need to combine a cellTemplate and sce.

{
  displayName: "First Name",
  field: "company",
  cellTemplate: '<div ng-bind-html="COL_FIELD | trusted"></div>'
}

COL_FIELD is replaced by ui-grid to contain the right field binding. The cellTemplate uses ng-bind-html and the following trusted filter to display the unescaped HTML:

app.filter('trusted', function ($sce) {
  return function (value) {
    return $sce.trustAsHtml(value);
  }
});

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

Upvotes: 3

Related Questions