简体   繁体   中英

Embed javascript in angular ui-router view

I'm really sorry if this has already been answered, but I have no idea how to search for it since it seems so specific.

I've got an AngularJS app using ui-router to dynamically load multiple views into the same <ui-view> element. I want to use Jquery UI's tooltip function on one of the h3 elements loaded dynamically by ui-router, but I don't know where to put the initializer such that it runs after the h3 is in the DOM.

Things I've tried:

  • Embedding a <script> tag in the HTML partial that calls $("h3").tooltip()
  • Putting the script tag in the main parent HTML template - with and without a document.ready wrapper
  • Putting the tooltip() function call in one of the angular js files that's loading the partial (when I changed the line to just alert() , it seemed that this code was running right before the partial is rendered, so there are no <h3> s yet)

I'm very confused as to how I can run arbitrary javascript code on dynamically loaded elements ... I think the first method should have worked. Even when I make the <script> tag just contain a simple alert() , nothing happens.

Any ideas? I'm also happy to provide more information, but I think I can't show the actual code due to an NDA.

The approach you are taking to get that tooltip working is very wrong. Instead of trying to load a script dynamically inside a view, you should be wrapping the tooltip plugin inside a directive and assigning that directive to your h3 element. Or, even simpler, use Angular UI Bootstrap's Tooltip directive: http://angular-ui.github.io/bootstrap/

Mock code for custom directive:

'use strict';

angular.module('MyModule')
    .directive('tooltip', function () {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                // initialize jQuery tooltip
                // note element is a jqLite object with jQuery methods available
                // DO NOT ATTEMPT TO WRAP element WITH jQuery
                // ANGULAR CANNOT TRACK jQuery OBJECTS THAT
                //   ARE NOT WRAPPED WITH jqLite!!!
                element.tooltip(...);
            }
        };
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM