Uib-tooltip with html unsafe

4.2k Views Asked by At

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.

3

There are 3 best solutions below

2
On BEST ANSWER

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>');
    }
});
0
On

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>

0
On

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.