0

I have a problem with my tooltip. I have something like this

<span uib-tooltip="{{displayName()}}"></span>

and in js file

function displayName() {
return '<div>' + 
     name +
    'div' +
    '<b>something</b>'
}

So I have escape characters and I don't know how to deal with it. Obviously, I would like to display in my tooltip properly code, without "div" etc.

How can I deal with it? I know that earlier we can use tooltip-html-unsafe, but it's deprecated now.

emka26
  • 433
  • 1
  • 11
  • 28

3 Answers3

0

Parse the HTML as safe using the $sce service and use uib-tooltip-html as specified in the ui-bootstrap docs.

In HTML:

<span uib-tooltip-html="displayName()"></span>

In controller:

app.controller("AppCtrl", function ($scope, $sce) {
    $scope.displayName = function () {
        return $sce.parseAsHtml('<div>' + name + '</div><b>something</b>');
    }
});
Protozoid
  • 1,207
  • 1
  • 8
  • 16
  • You'll have to inject `$sce` into the controller in order for this to work. I like to create a filter that I can use anywhere I want to bind HTML in the view: `.filter('unsafe', function($sce) { return (input) => $sce.trustAsHtml(input); })`. Now you can use `| unsafe` anywhere you want to bind HTML. – Lex Jun 07 '18 at 15:21
  • Thanks. Also, that's a very elegant solution, nice! – Protozoid Jun 07 '18 at 15:23
0

I'm not sure if this is what you want, but

You can have a tooltip with a template, which will parse / compile your HTML for you. You would need to use uib-tooltip-template. Here is a demo:

var app = angular.module('myApp', ["ui.bootstrap"]);
app.controller('myCtrl', function($scope) {
  $scope.name = "'Any name'";
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap-tpls.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<body>
  <div ng-app="myApp" ng-controller="myCtrl">

    <span uib-tooltip-template="'tooltipTemplate.html'" tooltip-placement="bottom">Tooltip with a template</span>

    <!-- separate file -->
    <script type="text/ng-template" id="tooltipTemplate.html">
      <div>
        {{name}}
      </div>
      <b>something else</b>
    </script>

  </div>
</body>
</html>
Aleksey Solovey
  • 4,153
  • 3
  • 15
  • 34
0

Simply installing ngSanitize and including it in your app will allow you to use uib-tooltip-html (rather than uib-tooltip) without worrying about safety.

https://docs.angularjs.org/api/ngSanitize

After installing, you can include it in your app:

var app = angular.module('myApp', [...,'ngSanitize']);

And of course, make sure you include the plugin in your build files. Personally, this allowed me to replace a lot of old unsafe tooltips very easily during upgrades from previous versions.

3nails4you
  • 112
  • 1
  • 9