我一直在寻找使用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”指令以处理仅单击代码。不知道这是否有可能,但是我发现它对每个人都很有用。
随时分享您的意见!
您可以自己编写。我看了一下如何处理角度单击并使用在这里找到的代码对其进行了修改:jQuery分别将双击和单击绑定
<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 } }); } }; }])
这是一个例子
柱塞