0
我想弄清楚如何顯示一個隱藏的元素相對於被點擊的鏈接來觸發它。Angular ng點擊顯示彈出式相對於點擊元素
我知道如何使用ng-click和ng-show,但我似乎無法弄清楚如何定位與「clicked」元素相關的「shown」元素。
想法?
-Yellowradio
我想弄清楚如何顯示一個隱藏的元素相對於被點擊的鏈接來觸發它。Angular ng點擊顯示彈出式相對於點擊元素
我知道如何使用ng-click和ng-show,但我似乎無法弄清楚如何定位與「clicked」元素相關的「shown」元素。
想法?
-Yellowradio
有很多不同的方式,你可以這取決於你正在試圖彈出的事情複雜做。你可以很容易地創建一個處理所有事情的指令,包括在你的元素上掛鉤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操作/定位。
只需注意:如果彈出窗口的內容本身會包含角碼,則只需要$編譯服務。例如一個指令或ng-click – mcgraphix 2014-10-14 21:14:29