Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/415.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 多个事件上的AngularJS$scope.$_Javascript_Angularjs_Events - Fatal编程技术网

Javascript 多个事件上的AngularJS$scope.$

Javascript 多个事件上的AngularJS$scope.$,javascript,angularjs,events,Javascript,Angularjs,Events,我有一个场景,当我需要监听通过$scope.$emit传输的两个不同事件时,我只想在这两个事件都发生时才采取行动 例如,如果触发事件如下所示: $scope.$emit('first'); // do nothing $scope.$emit('second'); // execute something $scope.$emit('first'); // Do nothing $scope.$emit('first'); // Do nothing $scope.$emit('second')

我有一个场景,当我需要监听通过
$scope.$emit
传输的两个不同事件时,我只想在这两个事件都发生时才采取行动

例如,如果触发事件如下所示:

$scope.$emit('first');
// do nothing
$scope.$emit('second');
// execute something
$scope.$emit('first');
// Do nothing
$scope.$emit('first');
// Do nothing
$scope.$emit('second');
// execute something
var triggeredEvents = [];
$scope.$on('first', function() {
    notifyEventTriggered('first');
});

$scope.$on('second', function() {
    notifyEventTriggered('second');
});
function notifyEventTriggered(event) {
    if (triggeredEvents.indexOf(event) == -1) {
         triggeredEvents.push(event);
    }
    if (triggeredEvents.length > 1) {
        execute();
        triggeredEvents.length = 0;
    }
}
有什么东西是现成的吗?理想的

$scope.$on('first','second',function(){})

我考虑过做以下几点:

$scope.$emit('first');
// do nothing
$scope.$emit('second');
// execute something
$scope.$emit('first');
// Do nothing
$scope.$emit('first');
// Do nothing
$scope.$emit('second');
// execute something
var triggeredEvents = [];
$scope.$on('first', function() {
    notifyEventTriggered('first');
});

$scope.$on('second', function() {
    notifyEventTriggered('second');
});
function notifyEventTriggered(event) {
    if (triggeredEvents.indexOf(event) == -1) {
         triggeredEvents.push(event);
    }
    if (triggeredEvents.length > 1) {
        execute();
        triggeredEvents.length = 0;
    }
}
有没有更简单的方法?或者一些关于如何改进的建议?而不是为此创建服务


谢谢

没有内置的方法。我个人会将一个新方法附加到$rootScope,如下所示:


没有内在的方法可以做到这一点。我个人会将一个新方法附加到$rootScope,如下所示: