Angular ng-click显示相对于clicked元素的弹出窗口

时间:2014-10-09 17:02:00

标签: jquery angularjs

我试图找出如何显示相对于被点击以触发它的链接定位的隐藏元素。

我知道如何使用ng-click和ng-show,但我似乎无法弄清楚如何定位"显示"关于"点击的元素"元件。

思想?

-Yellowradio

1 个答案:

答案 0 :(得分:0)

根据您尝试弹出的内容的复杂程度,有很多不同的方法可以执行此操作。您可以轻松创建一个处理所有内容的指令,包括连接元素上的click事件,生成弹出内容的html,然后将其显示在正确的位置。整个示例的代码有点长,可以在这里发布,但这里是指令:

angular.module("myModule", []).directive("popupLauncher", function($rootScope, $compile) {
return {
    restrict: 'A',
    link: function(scope, element, attrs) {
        var popup = "<div class='popup'>" + attrs['popupLauncher'] + "</div>";
        element.click(function() {
            var popups = $(".popup");
            if (popups.length > 0) {
                 //if it exists remove it (this allows for only one popup at a time on the screen)  
                popups.remove();
            } else {
                //if it doesn't add it
                var compiledElement = $compile(popup)($rootScope.$new());
                $('body').append(compiledElement);
                //figure out the coordinates of where you want the popup
                var topOfTrigger = element.offset().top;
                var leftOfTrigger = element.offset().left;
                var rightOfTrigger = leftOfTrigger + parseInt(element.css("width")); //don't use width() as it doesn't include margins and padding
                var bottomOfTrigger = topOfTrigger + parseInt(element.css("height"))
                //this will position it at the bottom right of the clicked element but
                //using the variables above you can change that
                $(compiledElement).css("top", bottomOfTrigger)
                    .css("left", rightOfTrigger);

                //you may want to hook up a resize listener on the body to reposition if the 
                //popup is visible when the page resizes
                //also, you may want  a click event on the body to close it when you click off
                //right now this requires that you click on the trigger again

            }
        });
    }
}
});

这是重要的CSS:

.popup {

    position:absolute;
    background-color:#FFFFFF;
    border:1px solid #000000;
    padding:10px;
}

以下是如何使用它:

<button popup-launcher="this is the popup content">popup</button>

查看这个工作指令的小提琴和用于样式化弹出窗口的示例CSS:http://jsfiddle.net/mcgraphix/s8506hm8/

这使用了JQuery,但您可以轻松地自己进行DOM操作/定位。