我的网站上有一个由ng-show
控制的下拉菜单。当用户点击按钮时,他们会看到下拉列表。当他们再次点击时,隐藏下拉列表:
<div class="button" ng-click="show = !show">Click Me</div>
<div ng-show="show" ng-init="show = false">
<div>You can see me now!</div>
</div>
这很好用。但是,我想要的是show
如果用户点击窗口中不是带有“按钮”类的div的任何地方,则设置为false。我怎样才能做到这一点?
答案 0 :(得分:1)
最快/最简单的方法是将取消代码(ng-click="show=false"
)放在body
元素上,然后将$event.stopPropagation()
添加到现有的ng-click中。这样,每次单击按钮时,由于阻止了click事件向上传播,因此取消代码不会触发。但是,点击其他地方会触发ng-click
上的body
,以便取消代码运行。 Here's a fiddle这样做。
我认为稍微“更好”或“更有棱角”的方法可以获得相同的结果,即创建一个可以与ng-click并排放置的新click-off
指令。新指令可以(a)在目标元素上注册另一个点击处理程序,这将停止传播,以及(b)在body
元素上注册一个点击处理程序以触发您需要的任何取消代码。 Here's a fiddle for that approach
答案 1 :(得分:1)
HTML:
<div customDropdown>
<h4>Click here to see dropdown</h4>
<ul ng-show="dropdownVisible">
<li ng-click="doSomething()">Item #1</li>
<li ng-click="doSomething()">Item #2</li>
<li ng-click="doSomething()">Item #3</li>
</ul>
</div>
简单指令:
app.directive('customDropdown', ['$document', function($document) {
return {
restrict: 'A',
link: function(scope, el) {
// Switch dropdown visibility by clicking on 'target' element
el.on('click', function(event) {
event.preventDefault();
scope.dropdownVisible = !scope.dropdownVisible;
});
// Hide dropdown if clicked somewhere 'outside'
$document.on('click', function(event) {
scope.dropdownVisible = false;
return $document.off('click', event);
});
}
};
}]);
答案 2 :(得分:0)
app.directive('clickOnlyHere',function(){
return {
scope: {
clickOnlyHere: "="
},
link: function(scope, element, attrs) {
var clickHandler = function(event){
// we need to check if the click is within our element ( or its decedents).
var inside = (element[0] === event.target) ||
$(event.target).parents().index(element) !== -1;
var show = inside ? !scope.clickOnlyHere : false;
scope.$apply(function() {
scope.clickOnlyHere = show;
});
}
$(document).on('click', clickHandler);
// must remove the click handler after our scope is destroyed.
scope.$on('$destroy',function(){
$(document).off('click', clickHandler);
})
}
}
});
<div class="button" click-only-here="show">Click Me</div>
<div ng-show="show" ng-init="show = false">
<div>You can see me now!</div>
</div>
答案 3 :(得分:-1)
$window.addEventListener('click', function(e) {
//your code
});