0

If I put this:

<button type="button" class="btn btn-info" data-toggle="tooltip" data-placement="top" title="Tooltip on top">
  Tooltip on top
</button>

Inside the index.html file, just between the <body> tags, it works - I got the tooltip shown as it should be.

But If i put the same thing in a directive of ng-view - like this:

<div ng-view></div>

The button is shown but the tooltip is not get fired.

The ng-view contains another html template file, using the ngRoute module which contains the <button> tag as specified above.

It seems like jQuery cannot select elements that are located inside the AngularJS ng-view directive.

How could this be solved?

Raz Buchnik
  • 7,753
  • 14
  • 53
  • 96

2 Answers2

0

jQuery can and does select the button. However, AngularJS's digest loop is likely removing the tooltip content from the DOM. Outside of the element that hosts the AngularJS application, this does not apply (no pun intended). Furthermore tooltips popovers are added asynchronously.

To make AngularJS recognize the change

import $ from 'jquery';
import 'bootstrap';
import angular from 'angular';

run.$inject = ["$scope"];
function run($scope) {
  const tooltippedElements = $('[data-toggle="tooltip"]');
  tooltippedElements.on('hidden.bs.tooltip', onShownOrHidden);

  tooltippedElements.on('shown.bs.tooltip', onShownOrHidden);

  function onShownOrHidden() {
    if (!$scope.$phase()) {
      $scope.$apply();
    }
  }
} 

angular
  .module('app', [])
  .run(run);

But instead of going through all of thirs trouble, use angular-ui-bootstrap or something similar.

Aluan Haddad
  • 29,886
  • 8
  • 72
  • 84
0

I have found the answer:

jQuery selectors, like $('[data-toggle="tooltip"]').tooltip(); are getting actioned before ng-view is getting actioned.

Therefore tooltip selector is trying to select an element which is not already been loaded to the DOM.

The solution for this problem, is simple:

  1. Include jQuery before AngularJS scripts in the index.html file (at the end of the body tag).

  2. Add ng-if directive to each jQuery script that has selectors (but not to the main jQuery file), like this: <script src="assets/js/scripts.rtl.js" ng-if="initSrc"></script>

    1. Set $rootScope.initSrc=true after any directive/component is loaded.

All of the jQuery functions will be working properly.

Raz Buchnik
  • 7,753
  • 14
  • 53
  • 96