我已经使用下面的单选和多选下拉解决方案解决了我的问题。
- 以下解决方案可用于生产,因为它不会对性能产生任何影响
我的设计方法我为单选创建了如下指令:
.directive("selection", ['$document',
function ($document) {
-- your variable initialization--
--any other method if you have like I have --
$scope.change = function (item) {
-------- my implementation
};
$scope.selected = function (item) {
-------- my implementation
};
//Actual click event should be handled in link function
function link($scope, element, attributes, ngModel) {
--other methods if you have any--
element.bind('click', function(event) {
$scope.onElementClick = true;
$document.on("click", $scope.onClick);
});
$scope.onClick = function (event) {
if($scope.onElementClick && $scope.opened)
{
$scope.onElementClick = false;
return;
}
$scope.opened = false;
$scope.$apply(attributes.selection);
$document.off("click", $scope.onClick);
};
}
return {
restrict: 'E',
controller: controller,
link: link,
scope: true,
require: "ngModel",
templateUrl: 'your template file(e.g: filename.tpl.html)'
};
因此,只有当您单击任何单个选择下拉菜单时,上面的代码才会将单击事件与文档绑定,并且由于 $document.off("click", $scope.onClick);
对于多选下拉菜单,您需要处理特殊情况,例如,如果您单击元素,则不应关闭下拉菜单,否则您一次不能选择多个选项。因此,如果在元素内单击它,则必须停止单击事件的传播。请在您点击链接功能内的事件处理中进行以下更改:
.directive("multiSelection", ['$document',
function ($document) {
-- your variable initialization--
--any other method if you have like I have --
$scope.change = function (item) {
-------- my implementation
};
$scope.selected = function (item) {
-------- my implementation
};
//Actual click event should be handled in link function
function link($scope, element, attributes, ngModel) {
--other methods if you have any--
element.bind('click', function(event) {
$document.on("click", $scope.onClick);
event.stopPropagation();
});
$scope.onClick = function (event) {
$scope.opened = false;
$scope.$apply(attributes.multiSelect);
$document.off("click", $scope.onClick);
};
}
return {
restrict: 'E',
controller: controller,
link: link,
require: "ngModel",
templateUrl: 'your template file(e.g: filename.tpl.html)'
};
希望对你有帮助