AngularJS: Add line-break or HTML Elements in Angular Bootstrap UI Tooltip

Standard

In order to add line-break in tool-tip content for angular bootstrap tool-tip component, Please try to understand, There are three versions of the tool-tip: uib-tooltip, uib-tooltip-template, and uib-tooltip-html:

  • uib-tooltip – Takes text only and will escape any HTML provided.
  • uib-tooltip-html $ – Takes an expression that evaluates to an HTML string. Note that this HTML is not compiled. If compilation is required, please use the uib-tooltip-template attribute option instead. The user is responsible for ensuring the content is safe to put into the DOM!
  • uib-tooltip-template $ – Takes text that specifies the location of a template to use for the tooltip. Note that this needs to be wrapped in a tag.
    Reference

In order to add HTML element like <br> for new line/line-break use uib-tooltip-html instead of uib-tooltip, make sure you have enabled $sceProvider in module config and injected $sce in relevant controller.

$sceProvider

The $sceProvider provider allows developers to configure the $sce service.

  • enable/disable Strict Contextual Escaping (SCE) in a module
  • override the default implementation with a custom delegate

$sce

$sce is a service that provides Strict Contextual Escaping services to AngularJS.

Strict Contextual Escaping (SCE) is a mode in which AngularJS constrains bindings to only render trusted values. Its goal is to assist in writing code in a way that (a) is secure by default, and (b) makes auditing for security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
Reference

Module/Controller Code:

var app = angular
                .module("tooltipApp", ['ui.bootstrap'])
                .config(function($sceProvider) {
                          $sceProvider.enabled(false);
                });

app.controller("tooltipController", function($scope, $sce) {
    $scope.tooltipContent = $sce.trustAsHtml('Hello World </br></br>' + 
                                             'Dummy content after line-break ');
});

HTML Code:

<span ng-app="test" ng-controller="tooltipController">
    <span uib-tooltip-html="tooltipContent">
        Tooltip Content
    </span>
</span>

Output:

Advertisements