2

I am trying to add HTML inside an md-tooltip but haven't had any luck, even with ng-bind-html.

Without using ng-bind-html, the tooltip outputs:
Some html<br> <strong>card</strong>.
enter image description here

With it, my HTML outputs as a string:
Some html<br><strong>card</strong>
enter image description here

In my controller, I use this custom filter to compile HTML used within an ng-repeat:

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

This filter successfully works with other elements aside from tooltips.

The tooltip is written as:

<md-tooltip md-delay="1000" md-direction="bottom" class="tooltip-sort-display">
    <span ng-bind-html="categoryItem.ToolTip | unsafe">
</md-tooltip>

Please note, when I don't use a json variable and instead add static text to the tooltip, HTML has no trouble rendering

<md-tooltip md-delay="1000" md-direction="bottom" class="tooltip-sort-display">
    <strong>Tool</strong><br><em>tip</em>
</md-tooltip>


enter image description here

Any ideas on how I can make this work? I would put together an example, but my Angular skills aren't that advanced. I mainly do the front-end development off my colleagues' work.

christine
  • 89
  • 2
  • 3
  • 11
  • Are you getting any error(s) in devtools console? – lealceldeiro Oct 02 '18 at 21:01
  • There is nothing wrong with the code you've shown, the problem must be elsewhere. Proof: http://jsfiddle.net/sh0ber/goe0m1Lr/ – Dan Oct 02 '18 at 21:40
  • @sh0ber In your code you aren't using special html chars, that's the main problem of the question. Check your fiddle with special chars: http://jsfiddle.net/raymo9j2/ – The.Bear Oct 03 '18 at 00:43
  • @The.Bear Using special chars is not the recommended practice, and it's less readable as well as extra work. Have a look at the documentation example JS: https://docs.angularjs.org/api/ng/directive/ngBindHtml#examples – Dan Oct 03 '18 at 03:22
  • @sh0ber I agree with you, is better to avoid them, but is this case, I've just gave a solution for this special scenario. Thanks. – The.Bear Oct 03 '18 at 03:33

1 Answers1

2

In your case, your problem is that you are using HTML special chars. If not, your code will works fine. Anyways if you cannot avoid receive special chars, you can add the decode in your filter:

JSFIDDLE DEMO

.filter('unsafeSpecial', function($sce) {
  return function(value) {
    var txt = document.createElement("textarea");
    txt.innerHTML = value;
    return $sce.trustAsHtml(txt.value);
  }
})

And the you can use like this way:

HTML

<md-tooltip>
  <span ng-bind-html="msg | unsafeSpecial"></span>
</md-tooltip>

CONTROLLER

.controller('mainCtrl', function($scope) {
  $scope.msg = 'Some html&lt;br&gt;&lt;strong&gt;card&lt;/strong&gt;';
})


For more info about decode html topic, check this question if you want: HTML Entity Decode
The.Bear
  • 5,621
  • 2
  • 27
  • 33