Javascript angularjs在$document单击时关闭模式窗口
我整天都在做这个,我被卡住了。我有一个模式/对话框,当单击一个div时会出现(该div位于我试图创建排序选项的表的th中)。div触发ng click并将$scope变量设置为true或false。我需要在单击div之外的任何位置时隐藏该模式。此外,还有多个div显示模态。如果单击了另一个div,则隐藏当前模式并使用该$scope再次显示该模式Javascript angularjs在$document单击时关闭模式窗口,javascript,angularjs,web-applications,controller,Javascript,Angularjs,Web Applications,Controller,我整天都在做这个,我被卡住了。我有一个模式/对话框,当单击一个div时会出现(该div位于我试图创建排序选项的表的th中)。div触发ng click并将$scope变量设置为true或false。我需要在单击div之外的任何位置时隐藏该模式。此外,还有多个div显示模态。如果单击了另一个div,则隐藏当前模式并使用该$scope再次显示该模式 <table> <thead> <th>Category 1 <div class="optionbox
<table>
<thead>
<th>Category 1 <div class="optionbox" ng-click="showModal($event)"></th>
<th>Category 2 <div class="optionbox" ng-click="showModal($event)"></th>
<th>Category 3 <div class="optionbox" ng-click="showModal($event)"></th>
</thead>
</table>
模态指令:
angular.modal('app', []).directive('modal', function(){
return {
templateUrl : ...,
restrict : 'E',
link : function($scope, element, attrs){
...
$scope.$watch('isModalVisible', function(newVal, oldVal){
if(newVal){
element.slideUp(1000);
}else{
element.slideDown(1000);
}
}
}
关闭模式指令(设置为模式模板中的属性)
angular.modal('app',[]).directive('globalModalClose',function(){
返回{
链接:函数($scope,element,attrs){
$document.on('click',function(){
if(element.find('event.target').length()<1){
元素。隐藏()
}
});
}
我可能在这里遗漏了一些东西,但这里是我的问题。我单击div显示模式,然后立即关闭它。这是因为在我的$document.on侦听器之前调用了我的showmodel函数。我可以选择1)让click listener先触发,或者2)其他一些…click事件会在DOM中冒泡。因此,您的
$document
的click listener在打开模式后接收到与打开模式相同的click事件
您可以使用来阻止事件从DOM向上冒泡到其他单击侦听器。Angular允许将$event
传递到ng click
函数中(如您在HTML中所看到的,您将使用ng click=“showmodel($event)”传递)
因此,应用于您的代码,您可以执行以下操作:
$scope.showModal = function(event) {
event.stopPropagation();
$scope.isModalVisible = !$scope.isModalVisible;
};
谢谢你的回答。我会尽快测试它。当选择另一个div时,我还需要弹出窗口来关闭和重新打开。有什么想法吗?需要更多的细节。你能解释更多吗?div是表/网格的一部分。它包含像“排序升序”和“排序降序”这样的选项。单击列1的div时,我想显示弹出窗口。如果您立即选择列2 div,则由于全局单击,列1的弹出窗口将关闭,但由于单击新列div,弹出窗口将重新打开。
angular.modal('app', []).directive('globalModalClose', function(){
return {
link : function($scope, element, attrs){
$document.on('click', function(){
if(element.find('event.target').length() < 1){
element.hide()
}
});
}
$scope.showModal = function(event) {
event.stopPropagation();
$scope.isModalVisible = !$scope.isModalVisible;
};