[英]AngularJS trying to hide popup menu when outside area is clicked
I have my HTML set up in the following way: 我通过以下方式设置了HTML:
<div>
<a href="" ng-click="$scope.show_menu = !$scope.show_menu">Options</a>
<div class="options_box" ng-show="$scope.show_menu">
<button>Option1</button>
...
</div>
</div>
And here is my AngularJS code: 这是我的AngularJS代码:
myApp.controller('myController',
['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
$scope.show_menu = false;
$scope.$window.onclick = function(){
$scope.show_menu = false;
$scope.apply();
};
...
} ]);
When the page loads, I receive the following error: 页面加载时,我收到以下错误:
Cannot set property 'onclick' of undefined
If I remove my $window.onclick
bit of code, the error disappears and clicking the Options
button successfully opens/closes the options popup. 如果我删除了我的
$window.onclick
位代码,则错误消失并单击“ Options
按钮成功打开/关闭选项弹出窗口。 What is the correct way to ensure the menu is hidden when any area outside the popup menu is clicked? 单击弹出菜单外的任何区域时,确保隐藏菜单的正确方法是什么?
$window
isn't a property on the scope. $window
不是范围内的属性。 AngularJS $window documentation says $window
is a global object. AngularJS $窗口文档说
$window
是一个全局对象。 Vaidik is correct in the method to get $window
into your controller, so having done that you can write $window.onclick...
not $scope.$window
. Vaidik在将
$window
输入控制器的方法中是正确的,所以完成后你可以编写$window.onclick...
而不是$scope.$window
。
I'm not sure this is the answer you need though. 我不确定这是你需要的答案。 I would question if it would work if you clicked on a button outside of the menu, as the button would handle the click preventing to event from bubbling up (propagating) to the window...
如果你点击菜单外的按钮,我会质疑它是否会起作用,因为按钮会处理点击阻止事件冒泡(传播)到窗口......
If you have to click to hide the menu then perhaps you could click on the same button that opened it by toggling ng-show
? 如果你必须点击隐藏菜单,那么也许你可以通过切换
ng-show
点击打开它的同一个按钮?
Alternatively the menu could just hide when it looses focus ie the mouse moves outside the area of the menu - by adding an ng-blur
directive to your menu element. 或者,菜单可以在失去焦点时隐藏,即鼠标移动到菜单区域之外 - 通过向菜单元素添加
ng-blur
指令。
See ngBlur documentation . 请参阅ngBlur文档 。
You need to $window
like so: 你需要
$window
这样:
myApp.controller('myController',
['$scope', '$http', '$routeParams', '$window', function($scope, $http, $routeParams, $window) {
$scope.show_menu = false;
$scope.$window.onclick = function(){
$scope.show_menu = false;
$scope.apply();
};
...
} ]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.