gpt4 book ai didi

javascript - 使用 AngularJS 处理同一元素上的 ng-click 和 ng-dblclick

转载 作者:IT王子 更新时间:2023-10-29 03:12:22 25 4
gpt4 key购买 nike

我一直在寻找 AngularJS 的单击和双击事件处理,因为 AngularJS 总是只触发 ng-click 事件,即使我们的元素设置了 ng-dblclick 指令也是如此。

这里有一些工作代码供那些寻求解决方案的人使用:

JS:

function MyController($scope) {

var waitingForSecondClick = false;
$scope.singleClickAction = function() {

executingDoubleClick = false;
if (waitingForSecondClick) {
waitingForSecondClick = false;
executingDoubleClick = true;
return $scope.doubleClickAction();
}
waitingForSecondClick = true;

setTimeout(function() {
waitingForSecondClick = false;
return singleClickOnlyAction();
}, 250); // delay

/*
* Code executed with single AND double-click goes here.
* ...
*/

var singleClickOnlyAction = function() {
if (executingDoubleClick) return;

/*
* Code executed ONLY with single-click goes here.
* ...
*/

}

}

$scope.doubleClickAction = function() {

/*
* Code executed ONLY with double-click goes here.
* ...
*/

};

}

HTML:

<div ng-controller="MyController">
<a href="#" ng-click="singleClickAction()">CLICK</a>
</div>

所以我的问题是(因为我是 AngularJS 的新手):是否有人更有经验可以编写一些很好的指令来处理这两个事件?

在我看来,完美的方法是更改​​ ng-click、ng-dblclick 的行为并添加一些“ng-sglclick”指令来处理仅单击代码。不知道是否可行,但我发现它对每个人都非常有用。

随时分享您的意见!

最佳答案

你可以自己写。我查看了 Angular 如何处理点击并使用我在此处找到的代码对其进行了修改:Jquery bind double click and single click separately

<div sglclick="singleClick()" ng-dblClick="doubleClick()" style="height:200px;width:200px;background-color:black">


mainMod.controller('AppCntrl', ['$scope', function ($scope) {
$scope.singleClick = function() {
alert('Single Click');
}
$scope.doubleClick = function() {
alert('Double Click');
}
}])


mainMod.directive('sglclick', ['$parse', function($parse) {
return {
restrict: 'A',
link: function(scope, element, attr) {
var fn = $parse(attr['sglclick']);
var delay = 300, clicks = 0, timer = null;
element.on('click', function (event) {
clicks++; //count clicks
if(clicks === 1) {
timer = setTimeout(function() {
scope.$apply(function () {
fn(scope, { $event: event });
});
clicks = 0; //after action performed, reset counter
}, delay);
} else {
clearTimeout(timer); //prevent single-click action
clicks = 0; //after action performed, reset counter
}
});
}
};
}])

举个例子

Plunker

关于javascript - 使用 AngularJS 处理同一元素上的 ng-click 和 ng-dblclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20444409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com