如何创建具有 ng 事件等$event的自定义事件指令



我有这样的AngularJS指令:

(function () {
'use strict';
// better click that ingore drag
angular
.module('module')
.directive('exClick', exClick);
exClick.$inject = [];
function exClick() {
return {
restrict: 'A',
scope: {
exClick: '&'
},
link: function ($scope, $element) {
var isDragging = false;
function mousemove() {
isDragging = true;
$(window).off('mousemove', mousemove);
}
var timer;
$element.mousedown(function() {
isDragging = false;
// there is wierd issue where move is triggerd just
// after mousedown even without moving the cursor
timer = setTimeout(function() {
$(window).mousemove(mousemove);
}, 100);
}).mouseup(function(e) {
var wasDragging = isDragging;
isDragging = false;
clearTimeout(timer);
$(window).off('mousemove', mousemove);
if (!wasDragging) {
$scope.$apply($scope.exClick);
}
});
$scope.$on('$destroy', function() {
$(window).off('mousemove', mousemove);
$element.off('mousedown mouseup');
});
}
}
}
})();

我想像普通的ng事件一样使用,我在表格行和我ng-click="$event.stopPropagation()"的行控件上单击ng单击。我已经用 ex-click 替换了行,我想使用ex-click="$event.stopPropagation()".我可以使用 ng-mouseup 来防止事件发生,但我想知道如何使我的自定义事件的行为与本机 ng 事件相同。

我试过:

$scope.exClick({$event: e});

$scope.$event = e;
$scope.$apply();
$scope.exClick();

在源代码中找到 ngClick 是一种普通的 AngularJS 指令(它的添加方式不同,但它具有相同的编译和链接,因此它应该工作相同(。

作为参考,这里是代码的副本:

forEach(
'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
function(eventName) {
var directiveName = directiveNormalize('ng-' + eventName);
ngEventDirectives[directiveName] = ['$parse', '$rootScope', '$exceptionHandler', function($parse, $rootScope, $exceptionHandler) {
return createEventDirective($parse, $rootScope, $exceptionHandler, directiveName, eventName, forceAsyncEvents[eventName]);
}];
}
);
function createEventDirective($parse, $rootScope, $exceptionHandler, directiveName, eventName, forceAsync) {
return {
restrict: 'A',
compile: function($element, attr) {
// NOTE:
// We expose the powerful `$event` object on the scope that provides access to the Window,
// etc. This is OK, because expressions are not sandboxed any more (and the expression
// sandbox was never meant to be a security feature anyway).
var fn = $parse(attr[directiveName]);
return function ngEventHandler(scope, element) {
element.on(eventName, function(event) {
var callback = function() {
fn(scope, {$event: event});
};
if (!$rootScope.$$phase) {
scope.$apply(callback);
} else if (forceAsync) {
scope.$evalAsync(callback);
} else {
try {
callback();
} catch (error) {
$exceptionHandler(error);
}
}
});
};
}
};
}

相关内容

最新更新