简体   繁体   中英

Bootstrap popover directive logic not working inside AngularJS custom directive

Setup: angularjs v1.2.3, ui-bootstrap tpl 0.4.0

Problem: Directive "popover" from UI Bootstrap inside Custom directive "milestone". Milestone directive gets rendered including the popover tag, but popover logic does not work - showing and hiding the popover. Tried to compile the popover HTML before handing over to scope variable milestonesHTML but didn't work. Any ideas?

Code : (very minimalistic to reduce complexity)

//Controller Variable
$scope.milestonesHTML;

//Usage in HTML
<milestone>
</milestone>

//Directive definition
directive('milestone', function( $compile ) {
return {
    restrict: 'E',

    template: '<span class="test" ng-bind-html="milestonesHTML"></span>',

    link: function(scope, iElement, iAttrs) {
        var milesHtml = '<img popover="End-to-end support" width="20" height="20" src="./img/info.png"/>';
        var compiledMilesHtml = $compile(milesHtml)(scope);
        scope.milestonesHTML = compiledMilesHtml[0].outerHTML;
    }
};

Plunkr

I have made a Plunkr for that, see here

In your link function, you are compiling and linking the img where the popover directive is used.

var milesHtml = '<img popover="End-to-end support" width="20" height="20" src="./img/info.png"/>';
var compiledMilesHtml = $compile(milesHtml)(scope);

This hooks up DOM with events and scope and gives you a final node: compiledMilesHtml . You are then abandoning all of this and binding just the HTML into your displayed DOM

template: '<span class="test" ng-bind-html="milestonesHTML"></span>',

scope.milestonesHTML = compiledMilesHtml[0].outerHTML;

This is just text, and has no knowledge about how events are hooked up or what watchers on the scope or other workings should be doing to your element. All that remains is the original DOM transformations.

If you do need to compile the node manually, you can do so and insert the actual element, compiledMilesHtml , into the DOM with jQuery or jQLite. However, your template is already being compiled, linked and inserted into the DOM. Without any other special requirements, your img should just be placed in your template, where it will work fine.

template: '<span class="test"><img popover="End-to-end support" width="20" height="20" src="./img/info.png"/></span>'

Demo here . I have changed the attributes passed to the popover to match in the custom directive and HTML versions.

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