我正在尝试关闭我的跌幅,这是多选的。下面是我正在尝试的代码:
element.bind('click', function (event) {
event.stopPropagation();
});
$document.bind('click', function () {
$scope.opened = false;
$scope.$apply();
});
但是一旦我在下拉窗口外单击。单击即触发多次点击事件,对于下面的每次点击,代码块被调用n次,如= 40,90等,我猜它等于窗口中元素的数量:
$document.bind('click', function () {
$scope.opened = false;
$scope.$apply();
});
我在document.bind之后尝试了event.stopPropagation()
,但它没有用。
我在为multiselect创建的指令的link函数中编写了这些代码块。
答案 0 :(得分:3)
我认为这将解决您的问题
post: function ($scope, element, attrs, controller) {
element.on("click", function(){
console.log("in element Click event");
$scope.onElementClick = true;
$document.on("click", $scope.onClick);
});
$scope.onClick = function (event) {
if($scope.onElementClick)
{
$scope.onElementClick = false;
return;
}
$scope.$apply(attrs.clickAnywhereButHere)
$document.off("click", $scope.onClick);
};
}
答案 1 :(得分:0)
我已使用以下解决方案解决了我的问题,单个选择和多选下拉列表。
我的设计方法我已经创建了单选的指令,如下所示:
.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)'
};
所以上面的代码只有当你单击任何一个选择下拉列表时才会将click事件与文档绑定,并且因为$ 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)'
};
希望有所帮助