我正在尝试使用 Bootstrap 3.0.2 和 AngularJS 1.2 创建多选下拉列表。我可以打开下拉框并进行多选。但是,不起作用的是,当我单击菜单外的任何位置时,它不会关闭。截至目前,我将“筛选选择”按钮视为打开和关闭下拉框的开关,这对用户来说不是很友好。
单击菜单外时,如何关闭下拉框?
这是我目前所拥有的:
<div class="btn-group" data-ng-class="{open: openDropDown}">
<button class="btn btn-default" type="button" data-ng-click="openDropDown=!openDropDown">Filter Selections<span class="caret"></span></button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu">
<li><a href="">Item #1<span class="glyphicon glyphicon-ok-sign pull-right"></span></a></li>
<li><a href="">Item #2<span class="glyphicon glyphicon-ok-sign pull-right"></span></a></li>
<li><a href="">Item #3<span class="glyphicon glyphicon-ok-sign pull-right"></span></a></li>
<li><a href="">Check All</a></li>
<li><a href="">Uncheck All</a></li>
</ul>
</div>
我知道我需要以某种方式合并 bootstrap 代码:“.dropdown-backdrop”以在单击菜单外部时关闭下拉菜单。
Bootstrap 3 下拉用法:http://getbootstrap.com/javascript/#dropdowns
最佳答案
使用您当前拥有的解决方案来修复它的一种解决方案是添加自定义指令来处理该问题。
所以给“btn-group”div元素添加一个指令属性,document-switch-off="openDropDown" 并将以下指令添加到应用程序。
<div class="btn-group" data-ng-class="{open: openDropDown}" document-switch-off="openDropDown">
<button class="btn btn-default" type="button" data-ng-click="openDropDown=!openDropDown">Filter Selections<span class="caret"></span></button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu">
<li><a href="">Item #1<span class="glyphicon glyphicon-ok-sign pull-right"></span></a></li>
<li><a href="">Item #2<span class="glyphicon glyphicon-ok-sign pull-right"></span></a></li>
<li><a href="">Item #3<span class="glyphicon glyphicon-ok-sign pull-right"></span></a></li>
<li><a href="">Check All</a></li>
<li><a href="">Uncheck All</a></li>
</ul>
</div>
指令代码:
angular.module('app')
.directive('documentSwitchOff', [
'$parse',
'$timeout',
function ($parse,$timeout) {
return function (scope, element, attrs) {
var getter = $parse(attrs.documentSwitchOff);
var setter = getter.assign;
var clickInsideElement = false;
function elementClickHandler(){
clickInsideElement = true;
}
function documentClickHandler(){
if(!clickInsideElement){
scope.$apply(function(){
setter(scope,false);
});
}
clickInsideElement = false;
}
var bound = false;
scope.$watch(attrs.documentSwitchOff,function(newVal){
if(angular.isDefined(newVal)){
if(newVal){
$timeout(function(){
bound = true;
element.bind("click",elementClickHandler);
var doc = angular.element(document)
doc.bind('click',documentClickHandler);
},0);
}
else{
if(bound){
element.unbind("click",elementClickHandler);
angular.element(document).unbind('click',documentClickHandler);
bound = false;
}
}
}
});
scope.$on("$destroy",function(){
if(bound){
element.unbind("click",elementClickHandler);
angular.element(document).unbind('click',documentClickHandler);
bound = false;
}
});
}
}
]);
我有一个 fiddle 示例的链接,用于创建具有您喜欢的功能的自定义下拉列表,我会寻找它。
找不到原始的 plunk,但这里是快速示例:http://plnkr.co/Qijgpud12hPidKYlZbfS
关于javascript - 使用 Bootstrap 3 和 AngularJS 的多选下拉列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21505321/