2014-10-09 86 views

回答

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操作/定位。

+0

只需注意:如果弹出窗口的内容本身会包含角码,则只需要$编译服务。例如一个指令或ng-click – mcgraphix 2014-10-14 21:14:29